1pub 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#[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, #[serde(default)]
68 pub notify: bool,
69 #[serde(default)]
72 pub notify_target: Option<String>,
73 #[serde(default, skip_serializing_if = "Option::is_none")]
76 pub sandbox: Option<bool>,
77 #[serde(skip)]
83 pub prompt_file: Option<PathBuf>,
84}
85
86#[derive(Debug, Clone, Serialize, Deserialize)]
88pub struct TaskTemplate {
89 pub title: String,
90 #[serde(default)]
91 pub body: String,
92 #[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
103pub 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
123fn 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 }
143
144#[derive(Debug, Serialize, Deserialize)]
146struct ConfigFile {
147 #[serde(default)]
148 jobs: Vec<Job>,
149 #[serde(flatten)]
151 other: serde_norway::Mapping,
152}
153
154pub fn resolve_jobs_path() -> PathBuf {
161 let project = PathBuf::from(".orch.yml");
163 if project.exists() {
164 return project;
165 }
166
167 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 home::config_path().unwrap_or_else(|_| PathBuf::from(".orch/config.yml"))
179}
180
181pub 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#[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
280fn 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
296pub 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; };
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
343pub 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
371pub fn save_jobs(path: &PathBuf, jobs: &[Job]) -> anyhow::Result<()> {
373 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 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
399pub 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 let rewritten = rewrite_frontmatter_enabled(&original, value);
414 fs::write(path, rewritten).with_context(|| format!("writing {}", path.display()))?;
415 Ok(())
416}
417
418fn rewrite_frontmatter_enabled(content: &str, value: &str) -> String {
423 let Some(rest) = content
425 .strip_prefix("---\n")
426 .or_else(|| content.strip_prefix("---\r\n"))
427 else {
428 return content.to_string();
430 };
431
432 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..]; 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
466fn is_not_found_error(e: &anyhow::Error) -> bool {
472 e.chain().any(|cause| has_status(&cause.to_string(), 404))
474}
475
476pub 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 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 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 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 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, Some(_) => false, }
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 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, },
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 if should_clear_task_id {
674 state.active_task_id = None;
675 }
676
677 if should_skip {
678 continue;
679 }
680
681 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 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; }
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_job(job, &mut state, backend, store, repo, transport, base_dir).await;
727
728 if let Some(s) = store
730 && let Err(e) = s.upsert_job_state(&state).await
731 {
732 tracing::error!(
733 job_id = job.id,
734 ?e,
735 "failed to persist job state after execution"
736 );
737 }
738 }
739
740 Ok(())
741}
742
743static RUNNING_BASH: LazyLock<DashSet<(String, String)>> = LazyLock::new(DashSet::new);
745
746struct RunningBash {
748 key: (String, String),
749}
750
751impl RunningBash {
752 fn try_acquire(repo: &str, job_id: &str) -> Option<Self> {
753 let key = (repo.to_string(), job_id.to_string());
754 if RUNNING_BASH.insert(key.clone()) {
755 Some(Self { key })
756 } else {
757 None
758 }
759 }
760}
761
762impl Drop for RunningBash {
763 fn drop(&mut self) {
764 RUNNING_BASH.remove(&self.key);
765 }
766}
767
768fn spawn_bash_job(
769 guard: RunningBash,
770 job: Job,
771 mut state: JobState,
772 store: Option<Arc<TaskStore>>,
773 repo: String,
774 transport: Option<Arc<Transport>>,
775 base_dir: PathBuf,
776) {
777 tokio::spawn(async move {
778 let _guard = guard;
779 apply_bash_result(&job, &mut state, &base_dir).await;
780 if let Some(s) = &store
781 && let Err(e) = s.upsert_job_state(&state).await
782 {
783 tracing::error!(
784 job_id = job.id,
785 ?e,
786 "failed to persist job state after execution"
787 );
788 }
789 notify_job_result(&job, &state, &repo, transport.as_ref());
790 });
791}
792
793async fn apply_bash_result(job: &Job, state: &mut JobState, base_dir: &Path) {
794 let Some(cmd) = job.command.as_deref() else {
795 return;
796 };
797 let dir = resolve_job_dir(job, base_dir);
800 tracing::info!(job_id = job.id, cmd, dir = %dir.display(), "running bash command");
801
802 let timeout_secs: u64 = config::get("jobs.bash_timeout_seconds")
805 .ok()
806 .and_then(|s| s.parse().ok())
807 .unwrap_or(300);
808 let timeout = Duration::from_secs(timeout_secs);
809
810 match run_bash(cmd, &dir, timeout).await {
811 Ok(Ok(o)) if o.status.success() => {
812 state.last_task_status = Some("done".to_string());
813 }
814 Ok(Ok(o)) => {
815 let stderr = String::from_utf8_lossy(&o.stderr);
816 tracing::warn!(
817 job_id = job.id,
818 code = o.status.code(),
819 %stderr,
820 "bash command failed"
821 );
822 state.last_task_status = Some("failed".to_string());
823 }
824 Ok(Err(e)) => {
825 tracing::error!(job_id = job.id, ?e, "bash command error");
826 state.last_task_status = Some("failed".to_string());
827 }
828 Err(_) => {
829 tracing::error!(
830 job_id = job.id,
831 secs = timeout_secs,
832 "bash job timed out after {}s, child killed",
833 timeout_secs
834 );
835 state.last_task_status = Some("timeout".to_string());
836 }
837 }
838}
839
840async fn run_bash(
843 cmd: &str,
844 dir: &Path,
845 timeout: Duration,
846) -> result::Result<anyhow::Result<Output>, time::error::Elapsed> {
847 let mut command = Command::new("bash");
848 command
849 .arg("-c")
850 .arg(cmd)
851 .current_dir(dir)
852 .stdin(Stdio::null())
853 .stdout(Stdio::piped())
854 .stderr(Stdio::piped())
855 .kill_on_drop(true);
856 #[cfg(unix)]
857 command.process_group(0);
858
859 let child = match command.spawn() {
860 Ok(child) => child,
861 Err(e) => return Ok(Err(anyhow::anyhow!("failed to execute `bash`: {e}"))),
862 };
863 let pgid = child.id();
864 let out = time::timeout(timeout, child.wait_with_output()).await;
865
866 #[cfg(unix)]
867 if out.is_err()
868 && let Some(pgid) = pgid
869 {
870 cmd_mod::kill_process_group(pgid);
871 }
872
873 out.map(|r| r.map_err(|e| anyhow::anyhow!("failed to execute `bash`: {e}")))
874}
875
876pub async fn execute_job(
881 job: &Job,
882 state: &mut JobState,
883 backend: &Arc<dyn ExternalBackend>,
884 store: Option<&Arc<TaskStore>>,
885 repo: &str,
886 transport: Option<&Arc<Transport>>,
887 base_dir: &Path,
888) {
889 match job.r#type.as_str() {
890 "task" => {
891 if let Some(ref template) = job.task {
892 let body = match resolve_template_body(template, base_dir) {
893 Ok(b) => b,
894 Err(e) => {
895 tracing::error!(job_id = job.id, ?e, "failed to resolve task body");
896 state.last_task_status = Some("failed".to_string());
897 return;
898 }
899 };
900
901 if job.external {
902 let mut labels = template.labels.clone();
903 labels.push("scheduled".to_string());
904 labels.push(format!("job:{}", job.id));
905
906 if let Some(ref agent) = template.agent
907 && !agent.is_empty()
908 {
909 labels.push(format!("agent:{agent}"));
910 }
911
912 match backend.create_task(&template.title, &body, &labels).await {
913 Ok(ext_id) => {
914 tracing::info!(
915 job_id = job.id,
916 task_id = ext_id.0,
917 "created external task"
918 );
919 state.active_task_id = Some(ext_id.0);
920 state.last_task_status = Some("new".to_string());
921 }
922 Err(e) => {
923 tracing::error!(job_id = job.id, ?e, "failed to create external task");
924 state.last_task_status = Some("failed".to_string());
925 }
926 }
927 } else if let Some(s) = store {
928 match s
929 .create_internal(repo, &template.title, &body, "cron", &job.id, None)
930 .await
931 {
932 Ok(internal_id) => {
933 let task_id = format!("internal:{internal_id}");
934 tracing::info!(job_id = job.id, task_id, "created internal task");
935 state.active_task_id = Some(task_id);
936 state.last_task_status = Some("new".to_string());
937 }
938 Err(e) => {
939 tracing::error!(job_id = job.id, ?e, "failed to create internal task");
940 state.last_task_status = Some("failed".to_string());
941 }
942 }
943 } else {
944 tracing::error!(
945 job_id = job.id,
946 "no store available for internal task creation"
947 );
948 state.last_task_status = Some("failed".to_string());
949 }
950 }
951 }
952 "bash" => {
953 apply_bash_result(job, state, base_dir).await;
954 }
955 other => {
961 tracing::warn!(job_id = job.id, r#type = other, "unknown job type");
962 }
963 }
964
965 notify_job_result(job, state, repo, transport);
966}
967
968fn notify_job_result(job: &Job, state: &JobState, repo: &str, transport: Option<&Arc<Transport>>) {
969 if job.notify
970 && let Some(t) = transport
971 {
972 let status = state
973 .last_task_status
974 .as_deref()
975 .unwrap_or("unknown")
976 .to_string();
977 let summary = match status.as_str() {
978 "done" => format!("Job `{}` completed successfully.", job.id),
979 "failed" => format!("Job `{}` failed.", job.id),
980 "new" => format!("Job `{}` created a new task.", job.id),
981 other => format!("Job `{}` finished with status: {other}.", job.id),
982 };
983 let target = job
985 .notify_target
986 .clone()
987 .or_else(|| config::get("channels.telegram.chat_id").ok());
988 let notification = TaskNotification {
989 task_id: job.id.clone(),
990 title: format!("Job: {}", job.id),
991 status,
992 agent: "scheduler".to_string(),
993 duration_seconds: 0.0,
994 summary,
995 repo: Some(repo.to_string()),
996 notify_target: target,
997 pr_number: None,
998 };
999 t.push_notification(notification);
1000 }
1001}
1002
1003#[cfg(test)]
1008mod tests {
1009 use super::*;
1010 use crate::backends::test_helpers::NoopBackend;
1011 use std::env;
1012 use std::fs;
1013 use tempfile::tempdir;
1014
1015 fn write_config(dir: &Path, content: &str) -> PathBuf {
1016 let path = dir.join(".orch.yml");
1017 fs::write(&path, content).unwrap();
1018 path
1019 }
1020
1021 #[tokio::test]
1022 async fn run_bash_timeout_kills_the_child() {
1023 let tmp = tempdir().unwrap();
1024 let pid_file = tmp.path().join("pid");
1025 let cmd = format!("sleep 60 & echo $! > {}; wait", pid_file.display());
1026
1027 let out = run_bash(&cmd, Path::new("."), Duration::from_secs(1)).await;
1028 assert!(out.is_err(), "expected a timeout");
1029
1030 let pid: i32 = fs::read_to_string(&pid_file)
1031 .unwrap()
1032 .trim()
1033 .parse()
1034 .unwrap();
1035 let mut gone = false;
1036 for _ in 0..20 {
1037 if cmd_mod::raw_kill(pid, 0) != 0 {
1038 gone = true;
1039 break;
1040 }
1041 time::sleep(Duration::from_millis(100)).await;
1042 }
1043 assert!(gone, "grandchild {pid} still running after timeout");
1044 }
1045
1046 fn bash_job(id: &str, command: String, dir: Option<&str>) -> Job {
1047 Job {
1048 id: id.to_string(),
1049 r#type: "bash".to_string(),
1050 schedule: "* * * * *".to_string(),
1051 task: None,
1052 command: Some(command),
1053 dir: dir.map(str::to_string),
1054 enabled: true,
1055 external: false,
1056 notify: false,
1057 notify_target: None,
1058 sandbox: None,
1059 prompt_file: None,
1060 }
1061 }
1062
1063 async fn execute_bash(job: &Job, base_dir: &Path) -> JobState {
1064 let backend: Arc<dyn ExternalBackend> = Arc::new(NoopBackend);
1065 let mut state = JobState::new("owner/repo", &job.id);
1066 execute_job(
1067 job,
1068 &mut state,
1069 &backend,
1070 None,
1071 "owner/repo",
1072 None,
1073 base_dir,
1074 )
1075 .await;
1076 state
1077 }
1078
1079 fn read_recorded_cwd(path: &Path) -> PathBuf {
1080 let raw = fs::read_to_string(path).expect("bash command should have written cwd.txt");
1081 fs::canonicalize(raw.trim()).unwrap()
1082 }
1083
1084 #[tokio::test]
1085 async fn bash_job_runs_in_project_dir_not_process_cwd() {
1086 let project = tempdir().unwrap();
1087 let process_cwd = fs::canonicalize(env::current_dir().unwrap()).unwrap();
1088 let project_dir = fs::canonicalize(project.path()).unwrap();
1089 assert_ne!(
1090 process_cwd, project_dir,
1091 "setup: process cwd must differ from the project dir"
1092 );
1093
1094 let out_default = project.path().join("cwd-default.txt");
1095 let job = bash_job(
1096 "default-dir",
1097 format!("pwd > '{}'", out_default.display()),
1098 None,
1099 );
1100 let state = execute_bash(&job, project.path()).await;
1101 assert_eq!(
1102 state.last_task_status.as_deref(),
1103 Some("done"),
1104 "bash job with no dir should succeed in the project dir"
1105 );
1106 assert_eq!(
1107 read_recorded_cwd(&out_default),
1108 project_dir,
1109 "bash job with no dir must run in the project dir"
1110 );
1111
1112 let scripts = project.path().join("scripts");
1113 fs::create_dir(&scripts).unwrap();
1114 let out_relative = project.path().join("cwd-relative.txt");
1115 let job = bash_job(
1116 "relative-dir",
1117 format!("pwd > '{}'", out_relative.display()),
1118 Some("scripts"),
1119 );
1120 let state = execute_bash(&job, project.path()).await;
1121 assert_eq!(
1122 state.last_task_status.as_deref(),
1123 Some("done"),
1124 "bash job should succeed when relative dir resolves to an existing path"
1125 );
1126 assert_eq!(
1127 read_recorded_cwd(&out_relative),
1128 fs::canonicalize(&scripts).unwrap(),
1129 "relative dir must resolve against the project dir"
1130 );
1131
1132 let abs = tempdir().unwrap();
1133 let out_abs = project.path().join("cwd-absolute.txt");
1134 let job = bash_job(
1135 "absolute-dir",
1136 format!("pwd > '{}'", out_abs.display()),
1137 Some(abs.path().to_str().unwrap()),
1138 );
1139 let state = execute_bash(&job, project.path()).await;
1140 assert_eq!(
1141 state.last_task_status.as_deref(),
1142 Some("done"),
1143 "bash job should succeed when dir is an absolute path"
1144 );
1145 assert_eq!(
1146 read_recorded_cwd(&out_abs),
1147 fs::canonicalize(abs.path()).unwrap(),
1148 "absolute dir must be used as-is"
1149 );
1150 }
1151
1152 async fn tick_with_store(path: &Path, store: &Arc<TaskStore>, repo: &str) {
1153 let backend: Arc<dyn ExternalBackend> = Arc::new(NoopBackend);
1154 tick(path, &backend, Some(store), repo, None).await.unwrap();
1155 }
1156
1157 async fn wait_for_job_status(
1158 store: &TaskStore,
1159 repo: &str,
1160 job_id: &str,
1161 want: &str,
1162 ) -> Option<String> {
1163 for _ in 0..300 {
1164 let status = store
1165 .get_job_state(repo, job_id)
1166 .await
1167 .unwrap()
1168 .and_then(|s| s.last_task_status);
1169 if status.as_deref() == Some(want) {
1170 return status;
1171 }
1172 time::sleep(Duration::from_millis(50)).await;
1173 }
1174 store
1175 .get_job_state(repo, job_id)
1176 .await
1177 .unwrap()
1178 .and_then(|s| s.last_task_status)
1179 }
1180
1181 #[tokio::test]
1182 async fn bash_job_tick_returns_before_the_command_ends() {
1183 let tmp = tempdir().unwrap();
1184 let cfg = write_config(
1185 tmp.path(),
1186 r#"
1187jobs:
1188 - id: slow
1189 type: bash
1190 schedule: "* * * * *"
1191 command: "sleep 5"
1192"#,
1193 );
1194 let store = Arc::new(TaskStore::open_memory().await.unwrap());
1195 let repo = "tick-returns/repo";
1196 let started = time::Instant::now();
1197 tick_with_store(&cfg, &store, repo).await;
1198 assert!(
1199 started.elapsed() < Duration::from_secs(2),
1200 "tick waited for the bash command, elapsed {:?}",
1201 started.elapsed()
1202 );
1203 let early = store.get_job_state(repo, "slow").await.unwrap().unwrap();
1204 assert!(
1205 early.last_run.is_some(),
1206 "last_run must be written before the command ends"
1207 );
1208 assert_ne!(
1209 early.last_task_status.as_deref(),
1210 Some("done"),
1211 "job state must not already be done when tick returns"
1212 );
1213 let status = wait_for_job_status(&store, repo, "slow", "done").await;
1214 assert_eq!(status.as_deref(), Some("done"));
1215 }
1216
1217 #[tokio::test]
1218 async fn bash_job_tick_starts_only_one_run() {
1219 let tmp = tempdir().unwrap();
1220 let log = tmp.path().join("runs.log");
1221 let go = tmp.path().join("go");
1222 let cfg = write_config(
1223 tmp.path(),
1224 &format!(
1225 r#"
1226jobs:
1227 - id: once
1228 type: bash
1229 schedule: "* * * * *"
1230 command: "echo x >> '{log}'; while [ ! -f '{go}' ]; do sleep 0.05; done"
1231"#,
1232 log = log.display(),
1233 go = go.display(),
1234 ),
1235 );
1236 let store = Arc::new(TaskStore::open_memory().await.unwrap());
1237 let repo = "tick-one-run/repo";
1238 tick_with_store(&cfg, &store, repo).await;
1239
1240 for _ in 0..100 {
1241 if log.exists() {
1242 break;
1243 }
1244 time::sleep(Duration::from_millis(20)).await;
1245 }
1246 assert!(log.exists(), "first bash job never started");
1247
1248 let mut state = store
1249 .get_job_state(repo, "once")
1250 .await
1251 .unwrap()
1252 .expect("last_run written before spawn");
1253 let past = chrono::Utc::now() - chrono::Duration::minutes(2);
1254 state.last_run = Some(past.format("%Y-%m-%dT%H:%M:%SZ").to_string());
1255 store.upsert_job_state(&state).await.unwrap();
1256
1257 tick_with_store(&cfg, &store, repo).await;
1258 fs::write(&go, "").unwrap();
1259 let status = wait_for_job_status(&store, repo, "once", "done").await;
1260 assert_eq!(status.as_deref(), Some("done"));
1261 let body = fs::read_to_string(&log).unwrap();
1262 assert_eq!(
1263 body.matches('x').count(),
1264 1,
1265 "started a second copy: {body:?}"
1266 );
1267 }
1268
1269 #[test]
1270 fn load_jobs_reads_prompt_from_file() {
1271 let tmp = tempdir().unwrap();
1272 fs::create_dir(tmp.path().join("prompts")).unwrap();
1273 fs::write(tmp.path().join("prompts/hello.md"), "hello from file").unwrap();
1274 let cfg = write_config(
1275 tmp.path(),
1276 r#"
1277jobs:
1278 - id: with-prompt
1279 schedule: "0 9 * * *"
1280 task:
1281 title: "Daily"
1282 prompt: prompts/hello.md
1283"#,
1284 );
1285
1286 let jobs = load_jobs(&cfg).unwrap();
1287 assert_eq!(jobs.len(), 1);
1288 let body = resolve_template_body(jobs[0].task.as_ref().unwrap(), tmp.path()).unwrap();
1289 assert_eq!(body, "hello from file");
1290 }
1291
1292 #[test]
1293 fn load_jobs_rejects_both_body_and_prompt() {
1294 let tmp = tempdir().unwrap();
1295 fs::write(tmp.path().join("p.md"), "x").unwrap();
1296 let cfg = write_config(
1297 tmp.path(),
1298 r#"
1299jobs:
1300 - id: conflict
1301 schedule: "0 9 * * *"
1302 task:
1303 title: "x"
1304 body: "inline"
1305 prompt: p.md
1306"#,
1307 );
1308
1309 let err = load_jobs(&cfg).unwrap_err().to_string();
1310 assert!(err.contains("not both"), "unexpected error: {err}");
1311 }
1312
1313 #[test]
1314 fn load_jobs_rejects_missing_prompt_file() {
1315 let tmp = tempdir().unwrap();
1316 let cfg = write_config(
1317 tmp.path(),
1318 r#"
1319jobs:
1320 - id: missing
1321 schedule: "0 9 * * *"
1322 task:
1323 title: "x"
1324 prompt: does-not-exist.md
1325"#,
1326 );
1327
1328 let err = load_jobs(&cfg).unwrap_err().to_string();
1329 assert!(
1330 err.contains("prompt file not found"),
1331 "unexpected error: {err}"
1332 );
1333 }
1334
1335 #[test]
1336 fn resolve_template_body_falls_back_to_inline_body() {
1337 let tmp = tempdir().unwrap();
1338 let template = TaskTemplate {
1339 title: "t".to_string(),
1340 body: "inline body".to_string(),
1341 prompt: None,
1342 labels: vec![],
1343 agent: None,
1344 };
1345 assert_eq!(
1346 resolve_template_body(&template, tmp.path()).unwrap(),
1347 "inline body"
1348 );
1349 }
1350
1351 fn write_prompt_job(dir: &Path, name: &str, content: &str) {
1352 let jobs_dir = dir.join("prompts").join("jobs");
1353 fs::create_dir_all(&jobs_dir).unwrap();
1354 fs::write(jobs_dir.join(name), content).unwrap();
1355 }
1356
1357 #[test]
1358 fn scan_prompt_jobs_picks_up_frontmatter_files() {
1359 let tmp = tempdir().unwrap();
1360 write_prompt_job(
1361 tmp.path(),
1362 "morning.md",
1363 "---\nid: morning\nschedule: '0 9 * * *'\ntitle: Morning\nlabels: [daily]\nagent: claude\n---\n\nDo morning stuff.\n",
1364 );
1365 let jobs = scan_prompt_jobs(tmp.path()).unwrap();
1366 assert_eq!(jobs.len(), 1);
1367 assert_eq!(jobs[0].id, "morning");
1368 assert_eq!(jobs[0].schedule, "0 9 * * *");
1369 let task = jobs[0].task.as_ref().unwrap();
1370 assert_eq!(task.title, "Morning");
1371 assert_eq!(task.body, "Do morning stuff.\n");
1372 assert_eq!(task.labels, vec!["daily".to_string()]);
1373 assert_eq!(task.agent.as_deref(), Some("claude"));
1374 }
1375
1376 #[test]
1377 fn load_jobs_merges_inline_and_scanned() {
1378 let tmp = tempdir().unwrap();
1379 write_prompt_job(
1380 tmp.path(),
1381 "scanned.md",
1382 "---\nid: scanned\nschedule: '0 9 * * *'\ntitle: Scanned\n---\n\nbody\n",
1383 );
1384 let cfg = write_config(
1385 tmp.path(),
1386 r#"
1387jobs:
1388 - id: inline
1389 schedule: "0 10 * * *"
1390 task:
1391 title: "Inline"
1392 body: "x"
1393"#,
1394 );
1395 let jobs = load_jobs(&cfg).unwrap();
1396 let ids: Vec<&str> = jobs.iter().map(|j| j.id.as_str()).collect();
1397 assert!(ids.contains(&"inline"));
1398 assert!(ids.contains(&"scanned"));
1399 assert_eq!(jobs.len(), 2);
1400 }
1401
1402 #[test]
1403 fn load_jobs_rejects_duplicate_id_across_sources() {
1404 let tmp = tempdir().unwrap();
1405 write_prompt_job(
1406 tmp.path(),
1407 "dup.md",
1408 "---\nid: dup\nschedule: '0 9 * * *'\ntitle: Dup\n---\n\nbody\n",
1409 );
1410 let cfg = write_config(
1411 tmp.path(),
1412 r#"
1413jobs:
1414 - id: dup
1415 schedule: "0 10 * * *"
1416 task:
1417 title: "Dup inline"
1418 body: "x"
1419"#,
1420 );
1421 let err = load_jobs(&cfg).unwrap_err().to_string();
1422 assert!(err.contains("duplicate job id"), "unexpected error: {err}");
1423 }
1424
1425 #[tokio::test]
1426 async fn a_job_with_sandbox_false_turns_it_off_for_its_task_only() {
1427 let dir = tempfile::tempdir().unwrap();
1428 let jobs_dir = dir.path().join("prompts/jobs");
1429 fs::create_dir_all(&jobs_dir).unwrap();
1430 fs::write(
1431 jobs_dir.join("mail.md"),
1432 "---\nid: mail\nschedule: '0 8 * * *'\ntitle: Mail\nsandbox: false\n---\n\nbody\n",
1433 )
1434 .unwrap();
1435 fs::write(
1436 jobs_dir.join("other.md"),
1437 "---\nid: other\nschedule: '0 8 * * *'\ntitle: Other\n---\n\nbody\n",
1438 )
1439 .unwrap();
1440 let store = TaskStore::open_memory().await.unwrap();
1441 for (job, task) in [("mail", "internal:1"), ("other", "internal:2")] {
1442 let mut state = JobState::new("owner/repo", job);
1443 state.active_task_id = Some(task.to_string());
1444 store.upsert_job_state(&state).await.unwrap();
1445 }
1446
1447 assert!(sandbox_off_for(&store, "owner/repo", dir.path(), "internal:1").await);
1448 assert!(!sandbox_off_for(&store, "owner/repo", dir.path(), "internal:2").await);
1449 assert!(!sandbox_off_for(&store, "owner/repo", dir.path(), "internal:3").await);
1450 }
1451
1452 #[test]
1453 fn scan_prompt_jobs_ignores_files_without_frontmatter() {
1454 let tmp = tempdir().unwrap();
1455 write_prompt_job(
1456 tmp.path(),
1457 "plain.md",
1458 "just a prompt body, no frontmatter\n",
1459 );
1460 let jobs = scan_prompt_jobs(tmp.path()).unwrap();
1461 assert_eq!(jobs.len(), 0);
1462 }
1463
1464 #[test]
1465 fn load_jobs_works_without_config_file_when_directory_present() {
1466 let tmp = tempdir().unwrap();
1467 write_prompt_job(
1468 tmp.path(),
1469 "solo.md",
1470 "---\nid: solo\nschedule: '0 9 * * *'\ntitle: Solo\n---\n\nbody\n",
1471 );
1472 let missing_cfg = tmp.path().join(".orch.yml");
1473 let jobs = load_jobs(&missing_cfg).unwrap();
1474 assert_eq!(jobs.len(), 1);
1475 assert_eq!(jobs[0].id, "solo");
1476 }
1477
1478 #[test]
1481 fn scan_prompt_jobs_respects_enabled_false() {
1482 let tmp = tempdir().unwrap();
1483 write_prompt_job(
1484 tmp.path(),
1485 "disabled.md",
1486 "---\nid: disabled\nschedule: '0 9 * * *'\ntitle: Disabled\nenabled: false\n---\n\nbody\n",
1487 );
1488 let jobs = scan_prompt_jobs(tmp.path()).unwrap();
1489 assert_eq!(jobs.len(), 1);
1490 assert!(!jobs[0].enabled, "job should be disabled via frontmatter");
1491 }
1492
1493 #[test]
1494 fn scan_prompt_jobs_sets_prompt_file() {
1495 let tmp = tempdir().unwrap();
1496 write_prompt_job(
1497 tmp.path(),
1498 "morning.md",
1499 "---\nid: morning\nschedule: '0 9 * * *'\ntitle: Morning\n---\n\nbody\n",
1500 );
1501 let jobs = scan_prompt_jobs(tmp.path()).unwrap();
1502 assert_eq!(jobs.len(), 1);
1503 assert!(
1504 jobs[0].prompt_file.is_some(),
1505 "prompt_file should be set for frontmatter jobs"
1506 );
1507 }
1508
1509 #[test]
1510 fn save_jobs_does_not_persist_prompt_based_jobs() {
1511 let tmp = tempdir().unwrap();
1512 write_prompt_job(
1514 tmp.path(),
1515 "prompt.md",
1516 "---\nid: from-prompt\nschedule: '0 9 * * *'\ntitle: Prompt Job\n---\n\nbody\n",
1517 );
1518 let cfg = write_config(
1520 tmp.path(),
1521 "jobs:\n - id: inline\n schedule: \"0 10 * * *\"\n task:\n title: Inline\n body: x\n",
1522 );
1523 let jobs = load_jobs(&cfg).unwrap();
1524 assert_eq!(jobs.len(), 2);
1525
1526 save_jobs(&cfg, &jobs).unwrap();
1528
1529 let saved = load_jobs(&cfg).unwrap();
1530 assert_eq!(saved.len(), 2, "both jobs should still be loadable");
1531 let ids: Vec<&str> = saved.iter().map(|j| j.id.as_str()).collect();
1532 assert!(ids.contains(&"inline"));
1533 assert!(ids.contains(&"from-prompt"));
1534 }
1535
1536 #[test]
1537 fn rewrite_frontmatter_enabled_replaces_existing_value() {
1538 let input = "---\nid: foo\nschedule: daily\nenabled: true\ntitle: Foo\n---\n\nbody\n";
1539 let out = rewrite_frontmatter_enabled(input, "false");
1540 assert!(
1541 out.contains("enabled: false"),
1542 "should replace enabled: true"
1543 );
1544 assert!(!out.contains("enabled: true"), "old value must be gone");
1545 assert!(out.contains("body"), "body must be preserved");
1546 }
1547
1548 #[test]
1549 fn rewrite_frontmatter_enabled_inserts_when_absent() {
1550 let input = "---\nid: foo\nschedule: daily\ntitle: Foo\n---\n\nbody\n";
1551 let out = rewrite_frontmatter_enabled(input, "false");
1552 assert!(
1553 out.contains("enabled: false"),
1554 "should insert enabled: false"
1555 );
1556 assert!(out.contains("body"), "body must be preserved");
1557 }
1558
1559 #[test]
1560 fn set_frontmatter_enabled_writes_file() {
1561 let tmp = tempdir().unwrap();
1562 let path = tmp.path().join("job.md");
1563 fs::write(
1564 &path,
1565 "---\nid: foo\nschedule: daily\ntitle: Foo\nenabled: true\n---\n\nbody\n",
1566 )
1567 .unwrap();
1568 set_frontmatter_enabled(&path, false).unwrap();
1569 let content = fs::read_to_string(&path).unwrap();
1570 assert!(content.contains("enabled: false"));
1571 assert!(!content.contains("enabled: true"));
1572 }
1573
1574 #[tokio::test]
1575 async fn tick_keeps_active_task_id_when_the_store_lookup_fails() {
1576 let tmp = tempdir().unwrap();
1577 let cfg = write_config(
1578 tmp.path(),
1579 r#"
1580jobs:
1581 - id: nightly
1582 type: bash
1583 schedule: "* * * * *"
1584 command: "true"
1585"#,
1586 );
1587 let store = Arc::new(TaskStore::open_memory().await.unwrap());
1588 let mut state = JobState::new("owner/repo", "nightly");
1589 state.active_task_id = Some("internal:1".to_string());
1590 store.upsert_job_state(&state).await.unwrap();
1591 sqlx::query("DROP TABLE tasks")
1593 .execute(store.pool())
1594 .await
1595 .unwrap();
1596
1597 let backend: Arc<dyn ExternalBackend> = Arc::new(NoopBackend);
1598 tick(&cfg, &backend, Some(&store), "owner/repo", None)
1599 .await
1600 .unwrap();
1601
1602 let after = store
1603 .get_job_state("owner/repo", "nightly")
1604 .await
1605 .unwrap()
1606 .unwrap();
1607 assert_eq!(after.active_task_id.as_deref(), Some("internal:1"));
1608 assert_eq!(after.last_run, None, "the job must not run again");
1609 }
1610
1611 #[test]
1612 fn not_found_error_ignores_a_404_inside_the_issue_number() {
1613 let transient = anyhow::anyhow!(
1614 "GitHub API GET https://api.github.com/repos/o/r/issues/1404 failed (500 Internal Server Error): boom"
1615 );
1616 assert!(!is_not_found_error(&transient));
1617 let missing = anyhow::anyhow!(
1618 "GitHub API GET https://api.github.com/repos/o/r/issues/1404 failed (404 Not Found): Not Found"
1619 );
1620 assert!(is_not_found_error(&missing));
1621 }
1622}