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::{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 mut states = store.list_job_states(repo).await.unwrap_or_default();
352    overlay_pending_job_states(repo, &mut states);
353    let Some(job_id) = states
354        .into_iter()
355        .find(|s| s.active_task_id.as_deref() == Some(task_id))
356        .map(|s| s.job_id)
357    else {
358        return false;
359    };
360
361    let path = project_dir.join(".orch.yml");
362    let Ok(Ok(jobs)) = task::spawn_blocking(move || load_jobs(&path)).await else {
363        return false;
364    };
365
366    jobs.iter()
367        .any(|j| j.id == job_id && j.sandbox == Some(false))
368}
369
370/// Save jobs back to the config file, preserving all other keys.
371pub fn save_jobs(path: &PathBuf, jobs: &[Job]) -> anyhow::Result<()> {
372    // Read the existing file to preserve non-jobs keys
373    let mut file: ConfigFile = if path.exists() {
374        let content =
375            fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
376        serde_norway::from_str(&content).with_context(|| format!("parsing {}", path.display()))?
377    } else {
378        ConfigFile {
379            jobs: vec![],
380            other: serde_norway::Mapping::new(),
381        }
382    };
383
384    // Only persist inline jobs (those without a prompt_file source).
385    // Prompt-based jobs live in prompts/jobs/*.md and must not be duplicated
386    // into .orch.yml — doing so causes a "duplicate job id" error on the next
387    // load_jobs call.
388    file.jobs = jobs
389        .iter()
390        .filter(|j| j.prompt_file.is_none())
391        .cloned()
392        .collect();
393    let content = serde_norway::to_string(&file)?;
394    fs::write(path, content).with_context(|| format!("writing {}", path.display()))?;
395    Ok(())
396}
397
398/// Update the `enabled:` field in the YAML frontmatter of a prompt-based job
399/// file, preserving all other content unchanged.
400///
401/// The function rewrites only the `enabled:` line inside the opening `---`
402/// fence.  If the field is absent it is inserted before the closing `---`.
403pub fn set_frontmatter_enabled(path: &Path, enabled: bool) -> anyhow::Result<()> {
404    let original =
405        fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
406
407    let value = if enabled { "true" } else { "false" };
408
409    // Replace an existing `enabled: <anything>` line inside the frontmatter.
410    // We only touch the first YAML block (between the opening and first closing
411    // `---` fences) to avoid accidentally rewriting the body.
412    let rewritten = rewrite_frontmatter_enabled(&original, value);
413    fs::write(path, rewritten).with_context(|| format!("writing {}", path.display()))?;
414    Ok(())
415}
416
417/// Rewrite the `enabled:` key inside the first `---` fence block of `content`.
418///
419/// If the key is present, its value is replaced.  If absent, it is appended
420/// just before the closing `---` line.  The rest of the document is unchanged.
421fn rewrite_frontmatter_enabled(content: &str, value: &str) -> String {
422    // Locate the opening fence.
423    let Some(rest) = content
424        .strip_prefix("---\n")
425        .or_else(|| content.strip_prefix("---\r\n"))
426    else {
427        // No frontmatter: return unchanged.
428        return content.to_string();
429    };
430
431    // Find the closing fence.
432    let Some(close_pos) = rest.find("\n---\n").or_else(|| rest.find("\n---\r\n")) else {
433        return content.to_string();
434    };
435
436    let fm = &rest[..close_pos];
437    let after_close = &rest[close_pos..]; // starts with "\n---\n" or "\n---\r\n"
438
439    // Rebuild the frontmatter, replacing or inserting `enabled:`.
440    let new_line = format!("enabled: {value}");
441    let mut found = false;
442    let new_fm: String = fm
443        .lines()
444        .map(|line| {
445            if line == "enabled: true" || line == "enabled: false" || line.starts_with("enabled: ")
446            {
447                found = true;
448                new_line.clone()
449            } else {
450                line.to_string()
451            }
452        })
453        .collect::<Vec<_>>()
454        .join("\n");
455
456    let new_fm = if found {
457        new_fm
458    } else {
459        format!("{new_fm}\n{new_line}")
460    };
461
462    format!("---\n{new_fm}{after_close}")
463}
464
465/// Returns `true` if the error indicates a "not found" (404) response.
466///
467/// Used to distinguish permanent task deletion from transient API errors.
468/// A 404 should clear `active_task_id`; other errors (rate limit, 5xx,
469/// network timeout) should be retried next tick without losing the reference.
470fn is_not_found_error(e: &anyhow::Error) -> bool {
471    // The status is matched apart from the URL, which holds the issue number
472    e.chain().any(|cause| has_status(&cause.to_string(), 404))
473}
474
475/// Check all jobs and execute due ones.
476///
477/// Runtime state (last_run, active_task_id, last_task_status) is stored in
478/// SQLite via the `job_state` table, not in the YAML config file.
479pub async fn tick(
480    jobs_path: &Path,
481    backend: &Arc<dyn ExternalBackend>,
482    store: Option<&Arc<TaskStore>>,
483    repo: &str,
484    transport: Option<&Arc<Transport>>,
485) -> anyhow::Result<()> {
486    let jobs_path_clone = jobs_path.to_path_buf();
487    let jobs = match task::spawn_blocking(move || load_jobs(&jobs_path_clone))
488        .await
489        .map_err(|e| anyhow::anyhow!("load_jobs panicked: {e}"))
490        .and_then(|r| r)
491    {
492        Ok(j) => j,
493        Err(e) => {
494            tracing::error!(
495                path = %jobs_path.display(),
496                repo = %repo,
497                ?e,
498                "job config invalid — skipping scheduler tick for this project"
499            );
500            return Ok(());
501        }
502    };
503    let now = chrono::Utc::now();
504
505    for job in &jobs {
506        if !job.enabled {
507            continue;
508        }
509
510        // Load runtime state from SQLite
511        let mut state = if let Some(s) = store {
512            match s.get_job_state(repo, &job.id).await {
513                Ok(Some(st)) => st,
514                Ok(None) => JobState::new(repo, &job.id),
515                Err(e) => {
516                    tracing::error!(job_id = job.id, ?e, "failed to load job state, skipping");
517                    continue;
518                }
519            }
520        } else {
521            JobState::new(repo, &job.id)
522        };
523
524        // Retry a lost post-create write even when the job is not due
525        if let Some(pending) = pending_job_state(repo, &job.id) {
526            state.active_task_id.clone_from(&pending.active_task_id);
527            state.last_task_status.clone_from(&pending.last_task_status);
528            if let Some(s) = store
529                && persist_job_state(s, &pending).await.is_err()
530            {
531                continue;
532            }
533        }
534
535        // Check if schedule matches
536        let is_due = match &state.last_run {
537            Some(last) => match crate_cron::check(&job.schedule, Some(last)) {
538                Ok(v) => v,
539                Err(e) => {
540                    tracing::error!(
541                        job_id = job.id,
542                        schedule = job.schedule,
543                        ?e,
544                        "invalid cron expression, skipping"
545                    );
546                    continue;
547                }
548            },
549            None => match crate_cron::check(&job.schedule, None) {
550                Ok(v) => v,
551                Err(e) => {
552                    tracing::error!(
553                        job_id = job.id,
554                        schedule = job.schedule,
555                        ?e,
556                        "invalid cron expression, skipping"
557                    );
558                    continue;
559                }
560            },
561        };
562
563        if !is_due {
564            continue;
565        }
566
567        // Check if previous task is still active
568        let mut should_clear_task_id = false;
569        let mut should_skip = false;
570
571        if let Some(ref task_id) = state.active_task_id
572            && task_id.is_empty()
573        {
574            state.active_task_id = None;
575        }
576
577        if let Some(ref task_id) = state.active_task_id {
578            let task_id_clone = task_id.clone();
579            let is_active = if job.external {
580                // Check external (GitHub) task
581                match backend.get_task(&ExternalId(task_id_clone.clone())).await {
582                    Ok(task) => {
583                        let status = task.labels.iter().find(|l| l.starts_with("status:"));
584                        match status.map(String::as_str) {
585                            Some(
586                                "status:in_progress"
587                                | "status:routed"
588                                | "status:new"
589                                | "status:needs_review"
590                                | "status:in_review"
591                                | "status:approved"
592                                | "status:waiting",
593                            )
594                            | None => true, // no status label is treated as active
595                            Some(_) => false, // Terminal state
596                        }
597                    }
598                    Err(e) => {
599                        if is_not_found_error(&e) {
600                            tracing::warn!(
601                                job_id = job.id,
602                                task_id = task_id_clone,
603                                "active task not found (404), clearing active_task_id"
604                            );
605                            should_clear_task_id = true;
606                            state.last_task_status = Some("error".to_string());
607                        } else {
608                            tracing::warn!(
609                                job_id = job.id,
610                                task_id = task_id_clone,
611                                ?e,
612                                "transient error fetching active task, skipping tick (active_task_id preserved)"
613                            );
614                            should_skip = true;
615                        }
616                        false
617                    }
618                }
619            } else {
620                // Check internal task via store
621                if let Some(s) = store {
622                    match s.resolve_task_id(repo, &task_id_clone).await {
623                        Ok(Some(store_id)) => match s.get(store_id).await {
624                            Ok(task) => match task.status {
625                                TaskStatus::New
626                                | TaskStatus::Routed
627                                | TaskStatus::InProgress
628                                | TaskStatus::NeedsReview
629                                | TaskStatus::InReview
630                                | TaskStatus::Approved
631                                | TaskStatus::Waiting => true,
632                                _ => false, // Terminal state (Done, Blocked, Cancelled)
633                            },
634                            Err(e) => {
635                                tracing::warn!(
636                                    job_id = job.id,
637                                    task_id = task_id_clone,
638                                    ?e,
639                                    "transient error fetching internal task, skipping tick (active_task_id preserved)"
640                                );
641                                should_skip = true;
642                                false
643                            }
644                        },
645                        Ok(None) => {
646                            tracing::warn!(
647                                job_id = job.id,
648                                task_id = task_id_clone,
649                                "internal task not found in store, clearing active_task_id"
650                            );
651                            should_clear_task_id = true;
652                            false
653                        }
654                        Err(e) => {
655                            tracing::warn!(
656                                job_id = job.id,
657                                task_id = task_id_clone,
658                                ?e,
659                                "store error resolving internal task, skipping tick (active_task_id preserved)"
660                            );
661                            should_skip = true;
662                            false
663                        }
664                    }
665                } else {
666                    should_clear_task_id = true;
667                    false
668                }
669            };
670
671            if is_active {
672                tracing::debug!(
673                    job_id = job.id,
674                    task_id = task_id_clone,
675                    external = job.external,
676                    "skipping: previous task still active"
677                );
678                should_skip = true;
679            }
680        }
681
682        // Apply deferred mutations
683        if should_clear_task_id {
684            state.active_task_id = None;
685        }
686
687        if should_skip {
688            continue;
689        }
690
691        // Claim the slot before last_run so a still-running bash job is skipped
692        // without bumping last_run, and a failed last_run write drops the guard
693        let bash_guard = if job.r#type == "bash" {
694            let Some(guard) = RunningBash::try_acquire(repo, &job.id) else {
695                tracing::debug!(job_id = job.id, "skipping: bash job still running");
696                continue;
697            };
698            Some(guard)
699        } else {
700            None
701        };
702
703        tracing::info!(job_id = job.id, r#type = job.r#type, "job due, executing");
704
705        // Persist last_run BEFORE execution to prevent catch-up on restart.
706        // On restart the runtime state is loaded from SQLite, so writing
707        // last_run here ensures a crash during execution won't cause the
708        // job to be considered due again immediately.
709        state.last_run = Some(now.format("%Y-%m-%dT%H:%M:%SZ").to_string());
710        if let Some(s) = store
711            && let Err(e) = s.upsert_job_state(&state).await
712        {
713            tracing::error!(
714                job_id = job.id,
715                ?e,
716                "failed to persist job state before execution — skipping this tick to preserve restart safety"
717            );
718            continue; // retry next tick instead of risking duplicate execution
719        }
720
721        let base_dir = jobs_path.parent().unwrap_or_else(|| Path::new("."));
722        if let Some(guard) = bash_guard {
723            spawn_bash_job(
724                guard,
725                job.clone(),
726                state,
727                store.cloned(),
728                repo.to_string(),
729                transport.cloned(),
730                base_dir.to_path_buf(),
731            );
732            continue;
733        }
734
735        execute_and_save(job, &mut state, backend, store, repo, transport, base_dir).await;
736    }
737
738    Ok(())
739}
740
741/// Bash jobs this process has spawned and not yet finished, keyed by repo and job id
742static RUNNING_BASH: LazyLock<DashSet<(String, String)>> = LazyLock::new(DashSet::new);
743
744// Created task id waiting for a successful job_state upsert
745static PENDING_JOB_STATE: LazyLock<DashMap<(String, String), JobState>> =
746    LazyLock::new(DashMap::new);
747
748const JOB_STATE_PERSIST_ATTEMPTS: u32 = 2;
749
750/// Releases the in-process slot when the spawned bash job ends
751struct RunningBash {
752    key: (String, String),
753}
754
755impl RunningBash {
756    fn try_acquire(repo: &str, job_id: &str) -> Option<Self> {
757        let key = (repo.to_string(), job_id.to_string());
758        if RUNNING_BASH.insert(key.clone()) {
759            Some(Self { key })
760        } else {
761            None
762        }
763    }
764}
765
766impl Drop for RunningBash {
767    fn drop(&mut self) {
768        RUNNING_BASH.remove(&self.key);
769    }
770}
771
772fn spawn_bash_job(
773    guard: RunningBash,
774    job: Job,
775    mut state: JobState,
776    store: Option<Arc<TaskStore>>,
777    repo: String,
778    transport: Option<Arc<Transport>>,
779    base_dir: PathBuf,
780) {
781    tokio::spawn(async move {
782        let _guard = guard;
783        apply_bash_result(&job, &mut state, &base_dir).await;
784        if let Some(s) = &store
785            && let Err(e) = s.upsert_job_state(&state).await
786        {
787            tracing::error!(
788                job_id = job.id,
789                ?e,
790                "failed to persist job state after execution"
791            );
792        }
793        notify_job_result(&job, &state, &repo, transport.as_ref());
794    });
795}
796
797async fn apply_bash_result(job: &Job, state: &mut JobState, base_dir: &Path) {
798    let Some(cmd) = job.command.as_deref() else {
799        return;
800    };
801    // Unset `dir` and relative `dir` resolve against `base_dir`, the project dir.
802    // The brew service cwd is `/`, so `"."` and `"scripts"` would otherwise run there
803    let dir = resolve_job_dir(job, base_dir);
804    tracing::info!(job_id = job.id, cmd, dir = %dir.display(), "running bash command");
805
806    // Configurable timeout with 5-minute default. A hung command is killed so
807    // the next cron period can start a fresh run
808    let timeout_secs: u64 = config::get("jobs.bash_timeout_seconds")
809        .ok()
810        .and_then(|s| s.parse().ok())
811        .unwrap_or(300);
812    let timeout = Duration::from_secs(timeout_secs);
813
814    match run_bash(cmd, &dir, timeout).await {
815        Ok(Ok(o)) if o.status.success() => {
816            state.last_task_status = Some("done".to_string());
817        }
818        Ok(Ok(o)) => {
819            let stderr = String::from_utf8_lossy(&o.stderr);
820            tracing::warn!(
821                job_id = job.id,
822                code = o.status.code(),
823                %stderr,
824                "bash command failed"
825            );
826            state.last_task_status = Some("failed".to_string());
827        }
828        Ok(Err(e)) => {
829            tracing::error!(job_id = job.id, ?e, "bash command error");
830            state.last_task_status = Some("failed".to_string());
831        }
832        Err(_) => {
833            tracing::error!(
834                job_id = job.id,
835                secs = timeout_secs,
836                "bash job timed out after {}s, child killed",
837                timeout_secs
838            );
839            state.last_task_status = Some("timeout".to_string());
840        }
841    }
842}
843
844/// Runs `bash -c` under a timeout in its own process group, so a timeout kills the commands bash
845/// forked too
846async fn run_bash(
847    cmd: &str,
848    dir: &Path,
849    timeout: Duration,
850) -> result::Result<anyhow::Result<Output>, time::error::Elapsed> {
851    let mut command = Command::new("bash");
852    command
853        .arg("-c")
854        .arg(cmd)
855        .current_dir(dir)
856        .stdin(Stdio::null())
857        .stdout(Stdio::piped())
858        .stderr(Stdio::piped())
859        .kill_on_drop(true);
860    #[cfg(unix)]
861    command.process_group(0);
862
863    let child = match command.spawn() {
864        Ok(child) => child,
865        Err(e) => return Ok(Err(anyhow::anyhow!("failed to execute `bash`: {e}"))),
866    };
867    let pgid = child.id();
868    let out = time::timeout(timeout, child.wait_with_output()).await;
869
870    #[cfg(unix)]
871    if out.is_err()
872        && let Some(pgid) = pgid
873    {
874        cmd_mod::kill_process_group(pgid);
875    }
876
877    out.map(|r| r.map_err(|e| anyhow::anyhow!("failed to execute `bash`: {e}")))
878}
879
880fn job_state_key(repo: &str, job_id: &str) -> (String, String) {
881    (repo.to_string(), job_id.to_string())
882}
883
884fn pending_job_state(repo: &str, job_id: &str) -> Option<JobState> {
885    PENDING_JOB_STATE
886        .get(&job_state_key(repo, job_id))
887        .map(|entry| (*entry).clone())
888}
889
890fn overlay_pending_job_states(repo: &str, states: &mut Vec<JobState>) {
891    for entry in PENDING_JOB_STATE.iter() {
892        let (key, pending) = entry.pair();
893        if key.0 != repo {
894            continue;
895        }
896        if let Some(existing) = states.iter_mut().find(|s| s.job_id == key.1) {
897            existing.active_task_id.clone_from(&pending.active_task_id);
898            existing
899                .last_task_status
900                .clone_from(&pending.last_task_status);
901        } else {
902            states.push(pending.clone());
903        }
904    }
905}
906
907async fn persist_job_state(store: &TaskStore, state: &JobState) -> anyhow::Result<()> {
908    let mut last_err = None;
909    for attempt in 1..=JOB_STATE_PERSIST_ATTEMPTS {
910        match store.upsert_job_state(state).await {
911            Ok(()) => {
912                PENDING_JOB_STATE.remove(&job_state_key(&state.repo, &state.job_id));
913                return Ok(());
914            }
915            Err(e) => {
916                tracing::error!(
917                    job_id = %state.job_id,
918                    attempt,
919                    ?e,
920                    "failed to persist job state after execution"
921                );
922                last_err = Some(e);
923            }
924        }
925    }
926    if state.active_task_id.is_some() {
927        PENDING_JOB_STATE.insert(job_state_key(&state.repo, &state.job_id), state.clone());
928    }
929    Err(last_err.expect("job state persist attempted at least once"))
930}
931
932/// Run the job and save its state, whose `active_task_id` is how the runner finds the job
933/// behind a task, for `sandbox: false`
934pub async fn execute_and_save(
935    job: &Job,
936    state: &mut JobState,
937    backend: &Arc<dyn ExternalBackend>,
938    store: Option<&Arc<TaskStore>>,
939    repo: &str,
940    transport: Option<&Arc<Transport>>,
941    base_dir: &Path,
942) {
943    execute_job(job, state, backend, store, repo, transport, base_dir).await;
944
945    if let Some(s) = store {
946        persist_job_state(s, state).await.ok();
947    }
948}
949
950pub async fn execute_job(
951    job: &Job,
952    state: &mut JobState,
953    backend: &Arc<dyn ExternalBackend>,
954    store: Option<&Arc<TaskStore>>,
955    repo: &str,
956    transport: Option<&Arc<Transport>>,
957    base_dir: &Path,
958) {
959    match job.r#type.as_str() {
960        "task" => {
961            if let Some(ref template) = job.task {
962                let body = match resolve_template_body(template, base_dir) {
963                    Ok(b) => b,
964                    Err(e) => {
965                        tracing::error!(job_id = job.id, ?e, "failed to resolve task body");
966                        state.last_task_status = Some("failed".to_string());
967                        return;
968                    }
969                };
970
971                if job.external {
972                    let mut labels = template.labels.clone();
973                    labels.push("scheduled".to_string());
974                    labels.push(format!("job:{}", job.id));
975
976                    if let Some(ref agent) = template.agent
977                        && !agent.is_empty()
978                    {
979                        labels.push(format!("agent:{agent}"));
980                    }
981
982                    match backend.create_task(&template.title, &body, &labels).await {
983                        Ok(ext_id) => {
984                            tracing::info!(
985                                job_id = job.id,
986                                task_id = ext_id.0,
987                                "created external task"
988                            );
989                            state.active_task_id = Some(ext_id.0);
990                            state.last_task_status = Some("new".to_string());
991                        }
992                        Err(e) => {
993                            tracing::error!(job_id = job.id, ?e, "failed to create external task");
994                            state.last_task_status = Some("failed".to_string());
995                        }
996                    }
997                } else if let Some(s) = store {
998                    match s
999                        .create_internal(repo, &template.title, &body, "cron", &job.id, None)
1000                        .await
1001                    {
1002                        Ok(internal_id) => {
1003                            let task_id = format!("internal:{internal_id}");
1004                            tracing::info!(job_id = job.id, task_id, "created internal task");
1005                            state.active_task_id = Some(task_id);
1006                            state.last_task_status = Some("new".to_string());
1007                        }
1008                        Err(e) => {
1009                            tracing::error!(job_id = job.id, ?e, "failed to create internal task");
1010                            state.last_task_status = Some("failed".to_string());
1011                        }
1012                    }
1013                } else {
1014                    tracing::error!(
1015                        job_id = job.id,
1016                        "no store available for internal task creation"
1017                    );
1018                    state.last_task_status = Some("failed".to_string());
1019                }
1020            }
1021        }
1022        "bash" => {
1023            apply_bash_result(job, state, base_dir).await;
1024        }
1025        // Note: previous versions supported a special-case "self-review"
1026        // job type with embedded analysis logic. That logic has been removed
1027        // — self-review work should be configured as a regular `task` job in
1028        // `.orch.yml` and executed by agents. Unknown job types fall through
1029        // to the warning handler below.
1030        other => {
1031            tracing::warn!(job_id = job.id, r#type = other, "unknown job type");
1032        }
1033    }
1034
1035    notify_job_result(job, state, repo, transport);
1036}
1037
1038fn notify_job_result(job: &Job, state: &JobState, repo: &str, transport: Option<&Arc<Transport>>) {
1039    if job.notify
1040        && let Some(t) = transport
1041    {
1042        let status = state
1043            .last_task_status
1044            .as_deref()
1045            .unwrap_or("unknown")
1046            .to_string();
1047        let summary = match status.as_str() {
1048            "done" => format!("Job `{}` completed successfully.", job.id),
1049            "failed" => format!("Job `{}` failed.", job.id),
1050            "new" => format!("Job `{}` created a new task.", job.id),
1051            other => format!("Job `{}` finished with status: {other}.", job.id),
1052        };
1053        // Resolve target chat_id: job override → config default
1054        let target = job
1055            .notify_target
1056            .clone()
1057            .or_else(|| config::get("channels.telegram.chat_id").ok());
1058        let notification = TaskNotification {
1059            task_id: job.id.clone(),
1060            title: format!("Job: {}", job.id),
1061            status,
1062            agent: "scheduler".to_string(),
1063            duration_seconds: 0.0,
1064            summary,
1065            repo: Some(repo.to_string()),
1066            notify_target: target,
1067            pr_number: None,
1068        };
1069        t.push_notification(notification);
1070    }
1071}
1072
1073// NOTE: self-review analysis is handled by scheduled `task` jobs configured
1074// in `.orch.yml` and executed by agents. There is no embedded Rust logic
1075// here — this module remains a generic job dispatcher.
1076
1077#[cfg(test)]
1078mod tests {
1079    use super::*;
1080    use crate::backends::test_helpers::NoopBackend;
1081    use std::env;
1082    use std::fs;
1083    use tempfile::tempdir;
1084
1085    fn write_config(dir: &Path, content: &str) -> PathBuf {
1086        let path = dir.join(".orch.yml");
1087        fs::write(&path, content).unwrap();
1088        path
1089    }
1090
1091    #[tokio::test]
1092    async fn run_bash_timeout_kills_the_child() {
1093        let tmp = tempdir().unwrap();
1094        let pid_file = tmp.path().join("pid");
1095        let cmd = format!("sleep 60 & echo $! > {}; wait", pid_file.display());
1096
1097        let out = run_bash(&cmd, Path::new("."), Duration::from_secs(1)).await;
1098        assert!(out.is_err(), "expected a timeout");
1099
1100        let pid: i32 = fs::read_to_string(&pid_file)
1101            .unwrap()
1102            .trim()
1103            .parse()
1104            .unwrap();
1105        let mut gone = false;
1106        for _ in 0..20 {
1107            if cmd_mod::raw_kill(pid, 0) != 0 {
1108                gone = true;
1109                break;
1110            }
1111            time::sleep(Duration::from_millis(100)).await;
1112        }
1113        assert!(gone, "grandchild {pid} still running after timeout");
1114    }
1115
1116    fn bash_job(id: &str, command: String, dir: Option<&str>) -> Job {
1117        Job {
1118            id: id.to_string(),
1119            r#type: "bash".to_string(),
1120            schedule: "* * * * *".to_string(),
1121            task: None,
1122            command: Some(command),
1123            dir: dir.map(str::to_string),
1124            enabled: true,
1125            external: false,
1126            notify: false,
1127            notify_target: None,
1128            sandbox: None,
1129            prompt_file: None,
1130        }
1131    }
1132
1133    async fn execute_bash(job: &Job, base_dir: &Path) -> JobState {
1134        let backend: Arc<dyn ExternalBackend> = Arc::new(NoopBackend);
1135        let mut state = JobState::new("owner/repo", &job.id);
1136        execute_job(
1137            job,
1138            &mut state,
1139            &backend,
1140            None,
1141            "owner/repo",
1142            None,
1143            base_dir,
1144        )
1145        .await;
1146        state
1147    }
1148
1149    fn read_recorded_cwd(path: &Path) -> PathBuf {
1150        let raw = fs::read_to_string(path).expect("bash command should have written cwd.txt");
1151        fs::canonicalize(raw.trim()).unwrap()
1152    }
1153
1154    #[tokio::test]
1155    async fn bash_job_runs_in_project_dir_not_process_cwd() {
1156        let project = tempdir().unwrap();
1157        let process_cwd = fs::canonicalize(env::current_dir().unwrap()).unwrap();
1158        let project_dir = fs::canonicalize(project.path()).unwrap();
1159        assert_ne!(
1160            process_cwd, project_dir,
1161            "setup: process cwd must differ from the project dir"
1162        );
1163
1164        let out_default = project.path().join("cwd-default.txt");
1165        let job = bash_job(
1166            "default-dir",
1167            format!("pwd > '{}'", out_default.display()),
1168            None,
1169        );
1170        let state = execute_bash(&job, project.path()).await;
1171        assert_eq!(
1172            state.last_task_status.as_deref(),
1173            Some("done"),
1174            "bash job with no dir should succeed in the project dir"
1175        );
1176        assert_eq!(
1177            read_recorded_cwd(&out_default),
1178            project_dir,
1179            "bash job with no dir must run in the project dir"
1180        );
1181
1182        let scripts = project.path().join("scripts");
1183        fs::create_dir(&scripts).unwrap();
1184        let out_relative = project.path().join("cwd-relative.txt");
1185        let job = bash_job(
1186            "relative-dir",
1187            format!("pwd > '{}'", out_relative.display()),
1188            Some("scripts"),
1189        );
1190        let state = execute_bash(&job, project.path()).await;
1191        assert_eq!(
1192            state.last_task_status.as_deref(),
1193            Some("done"),
1194            "bash job should succeed when relative dir resolves to an existing path"
1195        );
1196        assert_eq!(
1197            read_recorded_cwd(&out_relative),
1198            fs::canonicalize(&scripts).unwrap(),
1199            "relative dir must resolve against the project dir"
1200        );
1201
1202        let abs = tempdir().unwrap();
1203        let out_abs = project.path().join("cwd-absolute.txt");
1204        let job = bash_job(
1205            "absolute-dir",
1206            format!("pwd > '{}'", out_abs.display()),
1207            Some(abs.path().to_str().unwrap()),
1208        );
1209        let state = execute_bash(&job, project.path()).await;
1210        assert_eq!(
1211            state.last_task_status.as_deref(),
1212            Some("done"),
1213            "bash job should succeed when dir is an absolute path"
1214        );
1215        assert_eq!(
1216            read_recorded_cwd(&out_abs),
1217            fs::canonicalize(abs.path()).unwrap(),
1218            "absolute dir must be used as-is"
1219        );
1220    }
1221
1222    async fn tick_with_store(path: &Path, store: &Arc<TaskStore>, repo: &str) {
1223        let backend: Arc<dyn ExternalBackend> = Arc::new(NoopBackend);
1224        tick(path, &backend, Some(store), repo, None).await.unwrap();
1225    }
1226
1227    async fn wait_for_job_status(
1228        store: &TaskStore,
1229        repo: &str,
1230        job_id: &str,
1231        want: &str,
1232    ) -> Option<String> {
1233        for _ in 0..300 {
1234            let status = store
1235                .get_job_state(repo, job_id)
1236                .await
1237                .unwrap()
1238                .and_then(|s| s.last_task_status);
1239            if status.as_deref() == Some(want) {
1240                return status;
1241            }
1242            time::sleep(Duration::from_millis(50)).await;
1243        }
1244        store
1245            .get_job_state(repo, job_id)
1246            .await
1247            .unwrap()
1248            .and_then(|s| s.last_task_status)
1249    }
1250
1251    #[tokio::test]
1252    async fn bash_job_tick_returns_before_the_command_ends() {
1253        let tmp = tempdir().unwrap();
1254        let cfg = write_config(
1255            tmp.path(),
1256            r#"
1257jobs:
1258  - id: slow
1259    type: bash
1260    schedule: "* * * * *"
1261    command: "sleep 5"
1262"#,
1263        );
1264        let store = Arc::new(TaskStore::open_memory().await.unwrap());
1265        let repo = "tick-returns/repo";
1266        let started = time::Instant::now();
1267        tick_with_store(&cfg, &store, repo).await;
1268        assert!(
1269            started.elapsed() < Duration::from_secs(2),
1270            "tick waited for the bash command, elapsed {:?}",
1271            started.elapsed()
1272        );
1273        let early = store.get_job_state(repo, "slow").await.unwrap().unwrap();
1274        assert!(
1275            early.last_run.is_some(),
1276            "last_run must be written before the command ends"
1277        );
1278        assert_ne!(
1279            early.last_task_status.as_deref(),
1280            Some("done"),
1281            "job state must not already be done when tick returns"
1282        );
1283        let status = wait_for_job_status(&store, repo, "slow", "done").await;
1284        assert_eq!(status.as_deref(), Some("done"));
1285    }
1286
1287    #[tokio::test]
1288    async fn bash_job_tick_starts_only_one_run() {
1289        let tmp = tempdir().unwrap();
1290        let log = tmp.path().join("runs.log");
1291        let go = tmp.path().join("go");
1292        let cfg = write_config(
1293            tmp.path(),
1294            &format!(
1295                r#"
1296jobs:
1297  - id: once
1298    type: bash
1299    schedule: "* * * * *"
1300    command: "echo x >> '{log}'; while [ ! -f '{go}' ]; do sleep 0.05; done"
1301"#,
1302                log = log.display(),
1303                go = go.display(),
1304            ),
1305        );
1306        let store = Arc::new(TaskStore::open_memory().await.unwrap());
1307        let repo = "tick-one-run/repo";
1308        tick_with_store(&cfg, &store, repo).await;
1309
1310        for _ in 0..100 {
1311            if log.exists() {
1312                break;
1313            }
1314            time::sleep(Duration::from_millis(20)).await;
1315        }
1316        assert!(log.exists(), "first bash job never started");
1317
1318        let mut state = store
1319            .get_job_state(repo, "once")
1320            .await
1321            .unwrap()
1322            .expect("last_run written before spawn");
1323        let past = chrono::Utc::now() - chrono::Duration::minutes(2);
1324        state.last_run = Some(past.format("%Y-%m-%dT%H:%M:%SZ").to_string());
1325        store.upsert_job_state(&state).await.unwrap();
1326
1327        tick_with_store(&cfg, &store, repo).await;
1328        fs::write(&go, "").unwrap();
1329        let status = wait_for_job_status(&store, repo, "once", "done").await;
1330        assert_eq!(status.as_deref(), Some("done"));
1331        let body = fs::read_to_string(&log).unwrap();
1332        assert_eq!(
1333            body.matches('x').count(),
1334            1,
1335            "started a second copy: {body:?}"
1336        );
1337    }
1338
1339    #[test]
1340    fn load_jobs_reads_prompt_from_file() {
1341        let tmp = tempdir().unwrap();
1342        fs::create_dir(tmp.path().join("prompts")).unwrap();
1343        fs::write(tmp.path().join("prompts/hello.md"), "hello from file").unwrap();
1344        let cfg = write_config(
1345            tmp.path(),
1346            r#"
1347jobs:
1348  - id: with-prompt
1349    schedule: "0 9 * * *"
1350    task:
1351      title: "Daily"
1352      prompt: prompts/hello.md
1353"#,
1354        );
1355
1356        let jobs = load_jobs(&cfg).unwrap();
1357        assert_eq!(jobs.len(), 1);
1358        let body = resolve_template_body(jobs[0].task.as_ref().unwrap(), tmp.path()).unwrap();
1359        assert_eq!(body, "hello from file");
1360    }
1361
1362    #[test]
1363    fn load_jobs_rejects_both_body_and_prompt() {
1364        let tmp = tempdir().unwrap();
1365        fs::write(tmp.path().join("p.md"), "x").unwrap();
1366        let cfg = write_config(
1367            tmp.path(),
1368            r#"
1369jobs:
1370  - id: conflict
1371    schedule: "0 9 * * *"
1372    task:
1373      title: "x"
1374      body: "inline"
1375      prompt: p.md
1376"#,
1377        );
1378
1379        let err = load_jobs(&cfg).unwrap_err().to_string();
1380        assert!(err.contains("not both"), "unexpected error: {err}");
1381    }
1382
1383    #[test]
1384    fn load_jobs_rejects_missing_prompt_file() {
1385        let tmp = tempdir().unwrap();
1386        let cfg = write_config(
1387            tmp.path(),
1388            r#"
1389jobs:
1390  - id: missing
1391    schedule: "0 9 * * *"
1392    task:
1393      title: "x"
1394      prompt: does-not-exist.md
1395"#,
1396        );
1397
1398        let err = load_jobs(&cfg).unwrap_err().to_string();
1399        assert!(
1400            err.contains("prompt file not found"),
1401            "unexpected error: {err}"
1402        );
1403    }
1404
1405    #[test]
1406    fn resolve_template_body_falls_back_to_inline_body() {
1407        let tmp = tempdir().unwrap();
1408        let template = TaskTemplate {
1409            title: "t".to_string(),
1410            body: "inline body".to_string(),
1411            prompt: None,
1412            labels: vec![],
1413            agent: None,
1414        };
1415        assert_eq!(
1416            resolve_template_body(&template, tmp.path()).unwrap(),
1417            "inline body"
1418        );
1419    }
1420
1421    fn write_prompt_job(dir: &Path, name: &str, content: &str) {
1422        let jobs_dir = dir.join("prompts").join("jobs");
1423        fs::create_dir_all(&jobs_dir).unwrap();
1424        fs::write(jobs_dir.join(name), content).unwrap();
1425    }
1426
1427    #[test]
1428    fn scan_prompt_jobs_picks_up_frontmatter_files() {
1429        let tmp = tempdir().unwrap();
1430        write_prompt_job(
1431            tmp.path(),
1432            "morning.md",
1433            "---\nid: morning\nschedule: '0 9 * * *'\ntitle: Morning\nlabels: [daily]\nagent: claude\n---\n\nDo morning stuff.\n",
1434        );
1435        let jobs = scan_prompt_jobs(tmp.path()).unwrap();
1436        assert_eq!(jobs.len(), 1);
1437        assert_eq!(jobs[0].id, "morning");
1438        assert_eq!(jobs[0].schedule, "0 9 * * *");
1439        let task = jobs[0].task.as_ref().unwrap();
1440        assert_eq!(task.title, "Morning");
1441        assert_eq!(task.body, "Do morning stuff.\n");
1442        assert_eq!(task.labels, vec!["daily".to_string()]);
1443        assert_eq!(task.agent.as_deref(), Some("claude"));
1444    }
1445
1446    #[test]
1447    fn load_jobs_merges_inline_and_scanned() {
1448        let tmp = tempdir().unwrap();
1449        write_prompt_job(
1450            tmp.path(),
1451            "scanned.md",
1452            "---\nid: scanned\nschedule: '0 9 * * *'\ntitle: Scanned\n---\n\nbody\n",
1453        );
1454        let cfg = write_config(
1455            tmp.path(),
1456            r#"
1457jobs:
1458  - id: inline
1459    schedule: "0 10 * * *"
1460    task:
1461      title: "Inline"
1462      body: "x"
1463"#,
1464        );
1465        let jobs = load_jobs(&cfg).unwrap();
1466        let ids: Vec<&str> = jobs.iter().map(|j| j.id.as_str()).collect();
1467        assert!(ids.contains(&"inline"));
1468        assert!(ids.contains(&"scanned"));
1469        assert_eq!(jobs.len(), 2);
1470    }
1471
1472    #[test]
1473    fn load_jobs_rejects_duplicate_id_across_sources() {
1474        let tmp = tempdir().unwrap();
1475        write_prompt_job(
1476            tmp.path(),
1477            "dup.md",
1478            "---\nid: dup\nschedule: '0 9 * * *'\ntitle: Dup\n---\n\nbody\n",
1479        );
1480        let cfg = write_config(
1481            tmp.path(),
1482            r#"
1483jobs:
1484  - id: dup
1485    schedule: "0 10 * * *"
1486    task:
1487      title: "Dup inline"
1488      body: "x"
1489"#,
1490        );
1491        let err = load_jobs(&cfg).unwrap_err().to_string();
1492        assert!(err.contains("duplicate job id"), "unexpected error: {err}");
1493    }
1494
1495    #[tokio::test]
1496    async fn a_job_run_by_hand_links_its_task_so_sandbox_false_applies() {
1497        let dir = tempfile::tempdir().unwrap();
1498        let jobs_dir = dir.path().join("prompts/jobs");
1499        fs::create_dir_all(&jobs_dir).unwrap();
1500        fs::write(
1501            jobs_dir.join("mail.md"),
1502            "---\nid: mail\nschedule: '0 8 * * *'\ntitle: Mail\nsandbox: false\n---\n\nbody\n",
1503        )
1504        .unwrap();
1505        let job = load_jobs(&dir.path().join(".orch.yml")).unwrap().remove(0);
1506        let store = Arc::new(TaskStore::open_memory().await.unwrap());
1507        let backend: Arc<dyn ExternalBackend> = Arc::new(NoopBackend);
1508        let mut state = JobState::new("owner/repo", "mail");
1509
1510        execute_and_save(
1511            &job,
1512            &mut state,
1513            &backend,
1514            Some(&store),
1515            "owner/repo",
1516            None,
1517            dir.path(),
1518        )
1519        .await;
1520
1521        let task = state
1522            .active_task_id
1523            .clone()
1524            .expect("the run creates a task");
1525        let saved = store
1526            .get_job_state("owner/repo", "mail")
1527            .await
1528            .unwrap()
1529            .unwrap();
1530        assert_eq!(saved.active_task_id.as_deref(), Some(task.as_str()));
1531        assert!(sandbox_off_for(&store, "owner/repo", dir.path(), &task).await);
1532    }
1533
1534    #[tokio::test]
1535    async fn a_job_with_sandbox_false_turns_it_off_for_its_task_only() {
1536        let dir = tempfile::tempdir().unwrap();
1537        let jobs_dir = dir.path().join("prompts/jobs");
1538        fs::create_dir_all(&jobs_dir).unwrap();
1539        fs::write(
1540            jobs_dir.join("mail.md"),
1541            "---\nid: mail\nschedule: '0 8 * * *'\ntitle: Mail\nsandbox: false\n---\n\nbody\n",
1542        )
1543        .unwrap();
1544        fs::write(
1545            jobs_dir.join("other.md"),
1546            "---\nid: other\nschedule: '0 8 * * *'\ntitle: Other\n---\n\nbody\n",
1547        )
1548        .unwrap();
1549        let store = TaskStore::open_memory().await.unwrap();
1550        for (job, task) in [("mail", "internal:1"), ("other", "internal:2")] {
1551            let mut state = JobState::new("owner/repo", job);
1552            state.active_task_id = Some(task.to_string());
1553            store.upsert_job_state(&state).await.unwrap();
1554        }
1555
1556        assert!(sandbox_off_for(&store, "owner/repo", dir.path(), "internal:1").await);
1557        assert!(!sandbox_off_for(&store, "owner/repo", dir.path(), "internal:2").await);
1558        assert!(!sandbox_off_for(&store, "owner/repo", dir.path(), "internal:3").await);
1559    }
1560
1561    #[test]
1562    fn scan_prompt_jobs_ignores_files_without_frontmatter() {
1563        let tmp = tempdir().unwrap();
1564        write_prompt_job(
1565            tmp.path(),
1566            "plain.md",
1567            "just a prompt body, no frontmatter\n",
1568        );
1569        let jobs = scan_prompt_jobs(tmp.path()).unwrap();
1570        assert_eq!(jobs.len(), 0);
1571    }
1572
1573    #[test]
1574    fn load_jobs_works_without_config_file_when_directory_present() {
1575        let tmp = tempdir().unwrap();
1576        write_prompt_job(
1577            tmp.path(),
1578            "solo.md",
1579            "---\nid: solo\nschedule: '0 9 * * *'\ntitle: Solo\n---\n\nbody\n",
1580        );
1581        let missing_cfg = tmp.path().join(".orch.yml");
1582        let jobs = load_jobs(&missing_cfg).unwrap();
1583        assert_eq!(jobs.len(), 1);
1584        assert_eq!(jobs[0].id, "solo");
1585    }
1586
1587    // ──── Issue #3193: frontmatter `enabled: false` must be respected ────────
1588
1589    #[test]
1590    fn scan_prompt_jobs_respects_enabled_false() {
1591        let tmp = tempdir().unwrap();
1592        write_prompt_job(
1593            tmp.path(),
1594            "disabled.md",
1595            "---\nid: disabled\nschedule: '0 9 * * *'\ntitle: Disabled\nenabled: false\n---\n\nbody\n",
1596        );
1597        let jobs = scan_prompt_jobs(tmp.path()).unwrap();
1598        assert_eq!(jobs.len(), 1);
1599        assert!(!jobs[0].enabled, "job should be disabled via frontmatter");
1600    }
1601
1602    #[test]
1603    fn scan_prompt_jobs_sets_prompt_file() {
1604        let tmp = tempdir().unwrap();
1605        write_prompt_job(
1606            tmp.path(),
1607            "morning.md",
1608            "---\nid: morning\nschedule: '0 9 * * *'\ntitle: Morning\n---\n\nbody\n",
1609        );
1610        let jobs = scan_prompt_jobs(tmp.path()).unwrap();
1611        assert_eq!(jobs.len(), 1);
1612        assert!(
1613            jobs[0].prompt_file.is_some(),
1614            "prompt_file should be set for frontmatter jobs"
1615        );
1616    }
1617
1618    #[test]
1619    fn save_jobs_does_not_persist_prompt_based_jobs() {
1620        let tmp = tempdir().unwrap();
1621        // A prompt-based job
1622        write_prompt_job(
1623            tmp.path(),
1624            "prompt.md",
1625            "---\nid: from-prompt\nschedule: '0 9 * * *'\ntitle: Prompt Job\n---\n\nbody\n",
1626        );
1627        // An inline job in .orch.yml
1628        let cfg = write_config(
1629            tmp.path(),
1630            "jobs:\n  - id: inline\n    schedule: \"0 10 * * *\"\n    task:\n      title: Inline\n      body: x\n",
1631        );
1632        let jobs = load_jobs(&cfg).unwrap();
1633        assert_eq!(jobs.len(), 2);
1634
1635        // save_jobs should only write the inline job, not the prompt-based one
1636        save_jobs(&cfg, &jobs).unwrap();
1637
1638        let saved = load_jobs(&cfg).unwrap();
1639        assert_eq!(saved.len(), 2, "both jobs should still be loadable");
1640        let ids: Vec<&str> = saved.iter().map(|j| j.id.as_str()).collect();
1641        assert!(ids.contains(&"inline"));
1642        assert!(ids.contains(&"from-prompt"));
1643    }
1644
1645    #[test]
1646    fn rewrite_frontmatter_enabled_replaces_existing_value() {
1647        let input = "---\nid: foo\nschedule: daily\nenabled: true\ntitle: Foo\n---\n\nbody\n";
1648        let out = rewrite_frontmatter_enabled(input, "false");
1649        assert!(
1650            out.contains("enabled: false"),
1651            "should replace enabled: true"
1652        );
1653        assert!(!out.contains("enabled: true"), "old value must be gone");
1654        assert!(out.contains("body"), "body must be preserved");
1655    }
1656
1657    #[test]
1658    fn rewrite_frontmatter_enabled_inserts_when_absent() {
1659        let input = "---\nid: foo\nschedule: daily\ntitle: Foo\n---\n\nbody\n";
1660        let out = rewrite_frontmatter_enabled(input, "false");
1661        assert!(
1662            out.contains("enabled: false"),
1663            "should insert enabled: false"
1664        );
1665        assert!(out.contains("body"), "body must be preserved");
1666    }
1667
1668    #[test]
1669    fn set_frontmatter_enabled_writes_file() {
1670        let tmp = tempdir().unwrap();
1671        let path = tmp.path().join("job.md");
1672        fs::write(
1673            &path,
1674            "---\nid: foo\nschedule: daily\ntitle: Foo\nenabled: true\n---\n\nbody\n",
1675        )
1676        .unwrap();
1677        set_frontmatter_enabled(&path, false).unwrap();
1678        let content = fs::read_to_string(&path).unwrap();
1679        assert!(content.contains("enabled: false"));
1680        assert!(!content.contains("enabled: true"));
1681    }
1682
1683    #[tokio::test]
1684    async fn tick_keeps_active_task_id_when_the_store_lookup_fails() {
1685        let tmp = tempdir().unwrap();
1686        let cfg = write_config(
1687            tmp.path(),
1688            r#"
1689jobs:
1690  - id: nightly
1691    type: bash
1692    schedule: "* * * * *"
1693    command: "true"
1694"#,
1695        );
1696        let store = Arc::new(TaskStore::open_memory().await.unwrap());
1697        let mut state = JobState::new("owner/repo", "nightly");
1698        state.active_task_id = Some("internal:1".to_string());
1699        store.upsert_job_state(&state).await.unwrap();
1700        // Job state still reads, the task lookup now fails with a query error
1701        sqlx::query("DROP TABLE tasks")
1702            .execute(store.pool())
1703            .await
1704            .unwrap();
1705
1706        let backend: Arc<dyn ExternalBackend> = Arc::new(NoopBackend);
1707        tick(&cfg, &backend, Some(&store), "owner/repo", None)
1708            .await
1709            .unwrap();
1710
1711        let after = store
1712            .get_job_state("owner/repo", "nightly")
1713            .await
1714            .unwrap()
1715            .unwrap();
1716        assert_eq!(after.active_task_id.as_deref(), Some("internal:1"));
1717        assert_eq!(after.last_run, None, "the job must not run again");
1718    }
1719
1720    #[tokio::test]
1721    async fn tick_does_not_create_another_task_when_job_state_write_fails() {
1722        let tmp = tempdir().unwrap();
1723        let cfg = write_config(
1724            tmp.path(),
1725            r#"
1726jobs:
1727  - id: mail
1728    schedule: "* * * * *"
1729    sandbox: false
1730    task:
1731      title: Mail
1732      body: body
1733"#,
1734        );
1735        let store = Arc::new(TaskStore::open_memory().await.unwrap());
1736        let repo = "issue-4228/lost-persist";
1737        store.fail_next_job_state_writes(8);
1738
1739        tick_with_store(&cfg, &store, repo).await;
1740
1741        let tasks = store.list_all_internal(repo).await.unwrap();
1742        assert_eq!(tasks.len(), 1, "first tick should create one task");
1743        let task_id = format!("internal:{}", tasks[0].id);
1744        let saved = store
1745            .get_job_state(repo, "mail")
1746            .await
1747            .unwrap()
1748            .expect("last_run written before execute");
1749        assert_eq!(
1750            saved.active_task_id, None,
1751            "the created id must not be in SQLite after the upsert failed"
1752        );
1753        assert!(
1754            sandbox_off_for(&store, repo, tmp.path(), &task_id).await,
1755            "sandbox:false must still match the created task"
1756        );
1757
1758        let mut state = saved;
1759        let past = chrono::Utc::now() - chrono::Duration::minutes(2);
1760        state.last_run = Some(past.format("%Y-%m-%dT%H:%M:%SZ").to_string());
1761        store.upsert_job_state(&state).await.unwrap();
1762
1763        tick_with_store(&cfg, &store, repo).await;
1764
1765        let tasks = store.list_all_internal(repo).await.unwrap();
1766        assert_eq!(
1767            tasks.len(),
1768            1,
1769            "next period must not create another task while persist is outstanding"
1770        );
1771        assert!(sandbox_off_for(&store, repo, tmp.path(), &task_id).await);
1772    }
1773
1774    #[test]
1775    fn not_found_error_ignores_a_404_inside_the_issue_number() {
1776        let transient = anyhow::anyhow!(
1777            "GitHub API GET https://api.github.com/repos/o/r/issues/1404 failed (500 Internal Server Error): boom"
1778        );
1779        assert!(!is_not_found_error(&transient));
1780        let missing = anyhow::anyhow!(
1781            "GitHub API GET https://api.github.com/repos/o/r/issues/1404 failed (404 Not Found): Not Found"
1782        );
1783        assert!(is_not_found_error(&missing));
1784    }
1785}