1use crate::backends::{ExternalBackend, ExternalId};
17use crate::channels::notification::TaskNotification;
18use crate::channels::transport::Transport;
19use crate::cmd::CommandErrorContext;
20use crate::store::{JobState, TaskStatus};
21use anyhow::Context;
22use cron::Schedule;
23use serde::{Deserialize, Serialize};
24use std::path::{Path, PathBuf};
25use std::str::FromStr;
26use std::sync::Arc;
27
28#[derive(Debug, Clone, Serialize, Deserialize)]
34pub struct Job {
35 pub id: String,
36 #[serde(default = "default_job_type")]
37 pub r#type: String,
38 pub schedule: String,
39 #[serde(default)]
40 pub task: Option<TaskTemplate>,
41 #[serde(default)]
42 pub command: Option<String>,
43 #[serde(default)]
44 pub dir: Option<String>,
45 #[serde(default = "default_enabled")]
46 pub enabled: bool,
47 #[serde(default = "default_external")]
48 pub external: bool, #[serde(default)]
52 pub notify: bool,
53 #[serde(default)]
56 pub notify_target: Option<String>,
57 #[serde(skip)]
63 pub prompt_file: Option<PathBuf>,
64}
65
66#[derive(Debug, Clone, Serialize, Deserialize)]
68pub struct TaskTemplate {
69 pub title: String,
70 #[serde(default)]
71 pub body: String,
72 #[serde(default, skip_serializing_if = "Option::is_none")]
76 pub prompt: Option<String>,
77 #[serde(default)]
78 pub labels: Vec<String>,
79 #[serde(default)]
80 pub agent: Option<String>,
81}
82
83pub fn resolve_template_body(template: &TaskTemplate, base_dir: &Path) -> anyhow::Result<String> {
88 match template.prompt.as_deref() {
89 Some(rel) => {
90 let path = Path::new(rel);
91 let full = if path.is_absolute() {
92 path.to_path_buf()
93 } else {
94 base_dir.join(path)
95 };
96 std::fs::read_to_string(&full)
97 .with_context(|| format!("reading prompt file {}", full.display()))
98 }
99 None => Ok(template.body.clone()),
100 }
101}
102
103fn default_job_type() -> String {
104 "task".to_string()
105}
106
107fn default_enabled() -> bool {
108 true
109}
110
111fn default_external() -> bool {
112 false }
114
115#[derive(Debug, Serialize, Deserialize)]
117struct ConfigFile {
118 #[serde(default)]
119 jobs: Vec<Job>,
120 #[serde(flatten)]
122 other: serde_norway::Mapping,
123}
124
125pub fn resolve_jobs_path() -> PathBuf {
132 let project = PathBuf::from(".orch.yml");
134 if project.exists() {
135 return project;
136 }
137
138 if let Ok(paths) = crate::config::get_project_paths() {
140 for path_str in &paths {
141 let candidate = PathBuf::from(path_str).join(".orch.yml");
142 if candidate.exists() {
143 return candidate;
144 }
145 }
146 }
147
148 crate::home::config_path().unwrap_or_else(|_| PathBuf::from(".orch/config.yml"))
150}
151
152pub fn load_jobs(path: &PathBuf) -> anyhow::Result<Vec<Job>> {
158 let base_dir = path
159 .parent()
160 .map_or_else(|| PathBuf::from("."), Path::to_path_buf);
161 let mut jobs: Vec<Job> = if path.exists() {
162 let content =
163 std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
164 let file: ConfigFile = serde_norway::from_str(&content)
165 .with_context(|| format!("parsing {}", path.display()))?;
166 file.jobs
167 } else {
168 vec![]
169 };
170
171 let scanned = scan_prompt_jobs(&base_dir)?;
172 let mut seen: std::collections::HashSet<String> = jobs.iter().map(|j| j.id.clone()).collect();
173 for job in scanned {
174 if !seen.insert(job.id.clone()) {
175 anyhow::bail!(
176 "duplicate job id '{}' — defined in both '{}' and prompts/jobs/",
177 job.id,
178 path.display()
179 );
180 }
181 jobs.push(job);
182 }
183
184 for job in &jobs {
185 validate_job(job, &base_dir)?;
186 }
187 Ok(jobs)
188}
189
190fn validate_job(job: &Job, base_dir: &Path) -> anyhow::Result<()> {
191 let expanded = crate::cron::expand_alias(&job.schedule)
192 .with_context(|| format!("job '{}': invalid cron schedule '{}'", job.id, job.schedule))?;
193 let normalized = crate::cron::normalize_dow(&expanded);
194 let full_expr = format!("0 {normalized} *");
195 Schedule::from_str(&full_expr)
196 .with_context(|| format!("job '{}': invalid cron schedule '{}'", job.id, job.schedule))?;
197 if let Some(template) = job.task.as_ref() {
198 if template.prompt.is_some() && !template.body.is_empty() {
199 anyhow::bail!(
200 "job '{}': set either 'task.body' or 'task.prompt', not both",
201 job.id
202 );
203 }
204 if let Some(rel) = template.prompt.as_deref() {
205 let candidate = Path::new(rel);
206 let full = if candidate.is_absolute() {
207 candidate.to_path_buf()
208 } else {
209 base_dir.join(candidate)
210 };
211 if !full.exists() {
212 anyhow::bail!(
213 "job '{}': prompt file not found: {}",
214 job.id,
215 full.display()
216 );
217 }
218 }
219 }
220 Ok(())
221}
222
223#[derive(Debug, Deserialize)]
225struct JobFrontmatter {
226 id: String,
227 schedule: String,
228 title: String,
229 #[serde(default = "default_job_type")]
230 r#type: String,
231 #[serde(default = "default_enabled")]
232 enabled: bool,
233 #[serde(default = "default_external")]
234 external: bool,
235 #[serde(default)]
236 labels: Vec<String>,
237 #[serde(default)]
238 agent: Option<String>,
239 #[serde(default)]
240 notify: bool,
241 #[serde(default)]
242 notify_target: Option<String>,
243 #[serde(default)]
244 command: Option<String>,
245 #[serde(default)]
246 dir: Option<String>,
247}
248
249fn split_frontmatter(content: &str) -> Option<(&str, &str)> {
252 let rest = content
253 .strip_prefix("---\n")
254 .or_else(|| content.strip_prefix("---\r\n"))?;
255 let end = rest.find("\n---\n").or_else(|| rest.find("\n---\r\n"))?;
256 let fm = &rest[..end];
257 let after = &rest[end..];
258 let body = after
259 .strip_prefix("\n---\n")
260 .or_else(|| after.strip_prefix("\n---\r\n"))
261 .unwrap_or(after);
262 Some((fm, body.trim_start_matches('\n')))
263}
264
265pub fn scan_prompt_jobs(base_dir: &Path) -> anyhow::Result<Vec<Job>> {
267 let dir = base_dir.join("prompts").join("jobs");
268 if !dir.is_dir() {
269 return Ok(vec![]);
270 }
271 let mut entries: Vec<PathBuf> = std::fs::read_dir(&dir)
272 .with_context(|| format!("reading {}", dir.display()))?
273 .filter_map(std::result::Result::ok)
274 .map(|e| e.path())
275 .filter(|p| p.extension().and_then(|s| s.to_str()) == Some("md"))
276 .collect();
277 entries.sort();
278
279 let mut jobs = Vec::with_capacity(entries.len());
280 for path in entries {
281 let content = std::fs::read_to_string(&path)
282 .with_context(|| format!("reading {}", path.display()))?;
283 let Some((fm, body)) = split_frontmatter(&content) else {
284 continue; };
286 let meta: JobFrontmatter = serde_norway::from_str(fm)
287 .with_context(|| format!("parsing frontmatter in {}", path.display()))?;
288 jobs.push(Job {
289 id: meta.id,
290 r#type: meta.r#type,
291 schedule: meta.schedule,
292 task: Some(TaskTemplate {
293 title: meta.title,
294 body: body.to_string(),
295 prompt: None,
296 labels: meta.labels,
297 agent: meta.agent,
298 }),
299 command: meta.command,
300 dir: meta.dir,
301 enabled: meta.enabled,
302 external: meta.external,
303 notify: meta.notify,
304 notify_target: meta.notify_target,
305 prompt_file: Some(path.clone()),
306 });
307 }
308 Ok(jobs)
309}
310
311pub fn save_jobs(path: &PathBuf, jobs: &[Job]) -> anyhow::Result<()> {
313 let mut file: ConfigFile = if path.exists() {
315 let content =
316 std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
317 serde_norway::from_str(&content).with_context(|| format!("parsing {}", path.display()))?
318 } else {
319 ConfigFile {
320 jobs: vec![],
321 other: serde_norway::Mapping::new(),
322 }
323 };
324
325 file.jobs = jobs
330 .iter()
331 .filter(|j| j.prompt_file.is_none())
332 .cloned()
333 .collect();
334 let content = serde_norway::to_string(&file)?;
335 std::fs::write(path, content).with_context(|| format!("writing {}", path.display()))?;
336 Ok(())
337}
338
339pub fn set_frontmatter_enabled(path: &Path, enabled: bool) -> anyhow::Result<()> {
345 let original =
346 std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
347
348 let value = if enabled { "true" } else { "false" };
349
350 let rewritten = rewrite_frontmatter_enabled(&original, value);
354 std::fs::write(path, rewritten).with_context(|| format!("writing {}", path.display()))?;
355 Ok(())
356}
357
358fn rewrite_frontmatter_enabled(content: &str, value: &str) -> String {
363 let Some(rest) = content
365 .strip_prefix("---\n")
366 .or_else(|| content.strip_prefix("---\r\n"))
367 else {
368 return content.to_string();
370 };
371
372 let Some(close_pos) = rest.find("\n---\n").or_else(|| rest.find("\n---\r\n")) else {
374 return content.to_string();
375 };
376
377 let fm = &rest[..close_pos];
378 let after_close = &rest[close_pos..]; let new_line = format!("enabled: {value}");
382 let mut found = false;
383 let new_fm: String = fm
384 .lines()
385 .map(|line| {
386 if line == "enabled: true" || line == "enabled: false" || line.starts_with("enabled: ")
387 {
388 found = true;
389 new_line.clone()
390 } else {
391 line.to_string()
392 }
393 })
394 .collect::<Vec<_>>()
395 .join("\n");
396
397 let new_fm = if found {
398 new_fm
399 } else {
400 format!("{new_fm}\n{new_line}")
401 };
402
403 format!("---\n{new_fm}{after_close}")
404}
405
406fn is_not_found_error(e: &anyhow::Error) -> bool {
412 e.chain().any(|cause| cause.to_string().contains("404"))
416}
417
418pub async fn tick(
423 jobs_path: &Path,
424 backend: &Arc<dyn ExternalBackend>,
425 store: Option<&Arc<crate::store::TaskStore>>,
426 repo: &str,
427 transport: Option<&Arc<Transport>>,
428) -> anyhow::Result<()> {
429 let jobs_path_clone = jobs_path.to_path_buf();
430 let jobs = match tokio::task::spawn_blocking(move || load_jobs(&jobs_path_clone))
431 .await
432 .map_err(|e| anyhow::anyhow!("load_jobs panicked: {e}"))
433 .and_then(|r| r)
434 {
435 Ok(j) => j,
436 Err(e) => {
437 tracing::error!(
438 path = %jobs_path.display(),
439 repo = %repo,
440 ?e,
441 "job config invalid — skipping scheduler tick for this project"
442 );
443 return Ok(());
444 }
445 };
446 let now = chrono::Utc::now();
447
448 for job in &jobs {
449 if !job.enabled {
450 continue;
451 }
452
453 let mut state = if let Some(s) = store {
455 match s.get_job_state(repo, &job.id).await {
456 Ok(Some(st)) => st,
457 Ok(None) => JobState::new(repo, &job.id),
458 Err(e) => {
459 tracing::error!(job_id = job.id, ?e, "failed to load job state, skipping");
460 continue;
461 }
462 }
463 } else {
464 JobState::new(repo, &job.id)
465 };
466
467 let is_due = match &state.last_run {
469 Some(last) => match crate::cron::check(&job.schedule, Some(last)) {
470 Ok(v) => v,
471 Err(e) => {
472 tracing::error!(
473 job_id = job.id,
474 schedule = job.schedule,
475 ?e,
476 "invalid cron expression, skipping"
477 );
478 continue;
479 }
480 },
481 None => match crate::cron::check(&job.schedule, None) {
482 Ok(v) => v,
483 Err(e) => {
484 tracing::error!(
485 job_id = job.id,
486 schedule = job.schedule,
487 ?e,
488 "invalid cron expression, skipping"
489 );
490 continue;
491 }
492 },
493 };
494
495 if !is_due {
496 continue;
497 }
498
499 let mut should_clear_task_id = false;
501 let mut should_skip = false;
502
503 if let Some(ref task_id) = state.active_task_id
504 && task_id.is_empty()
505 {
506 state.active_task_id = None;
507 }
508
509 if let Some(ref task_id) = state.active_task_id {
510 let task_id_clone = task_id.clone();
511 let is_active = if job.external {
512 match backend.get_task(&ExternalId(task_id_clone.clone())).await {
514 Ok(task) => {
515 let status = task.labels.iter().find(|l| l.starts_with("status:"));
516 match status.map(std::string::String::as_str) {
517 Some(
518 "status:in_progress"
519 | "status:routed"
520 | "status:new"
521 | "status:needs_review"
522 | "status:in_review"
523 | "status:approved"
524 | "status:waiting",
525 )
526 | None => true, Some(_) => false, }
529 }
530 Err(e) => {
531 if is_not_found_error(&e) {
532 tracing::warn!(
533 job_id = job.id,
534 task_id = task_id_clone,
535 "active task not found (404), clearing active_task_id"
536 );
537 should_clear_task_id = true;
538 state.last_task_status = Some("error".to_string());
539 } else {
540 tracing::warn!(
541 job_id = job.id,
542 task_id = task_id_clone,
543 ?e,
544 "transient error fetching active task, skipping tick (active_task_id preserved)"
545 );
546 should_skip = true;
547 }
548 false
549 }
550 }
551 } else {
552 if let Some(s) = store {
554 if let Ok(Some(store_id)) = s.resolve_task_id(repo, &task_id_clone).await {
555 match s.get(store_id).await {
556 Ok(task) => match task.status {
557 TaskStatus::New
558 | TaskStatus::Routed
559 | TaskStatus::InProgress
560 | TaskStatus::NeedsReview
561 | TaskStatus::InReview
562 | TaskStatus::Approved
563 | TaskStatus::Waiting => true,
564 _ => false, },
566 Err(e) => {
567 tracing::warn!(
568 job_id = job.id,
569 task_id = task_id_clone,
570 ?e,
571 "cannot fetch internal task from store, clearing active_task_id"
572 );
573 should_clear_task_id = true;
574 false
575 }
576 }
577 } else {
578 tracing::warn!(
579 job_id = job.id,
580 task_id = task_id_clone,
581 "internal task not found in store, clearing active_task_id"
582 );
583 should_clear_task_id = true;
584 false
585 }
586 } else {
587 should_clear_task_id = true;
588 false
589 }
590 };
591
592 if is_active {
593 tracing::debug!(
594 job_id = job.id,
595 task_id = task_id_clone,
596 external = job.external,
597 "skipping: previous task still active"
598 );
599 should_skip = true;
600 }
601 }
602
603 if should_clear_task_id {
605 state.active_task_id = None;
606 }
607
608 if should_skip {
609 continue;
610 }
611
612 tracing::info!(job_id = job.id, r#type = job.r#type, "job due, executing");
613
614 state.last_run = Some(now.format("%Y-%m-%dT%H:%M:%SZ").to_string());
619 if let Some(s) = store
620 && let Err(e) = s.upsert_job_state(&state).await
621 {
622 tracing::error!(
623 job_id = job.id,
624 ?e,
625 "failed to persist job state before execution — skipping this tick to preserve restart safety"
626 );
627 continue; }
629
630 let base_dir = jobs_path.parent().unwrap_or_else(|| Path::new("."));
632 execute_job(job, &mut state, backend, store, repo, transport, base_dir).await;
633
634 if let Some(s) = store
636 && let Err(e) = s.upsert_job_state(&state).await
637 {
638 tracing::error!(
639 job_id = job.id,
640 ?e,
641 "failed to persist job state after execution"
642 );
643 }
644 }
645
646 Ok(())
647}
648
649pub async fn execute_job(
654 job: &Job,
655 state: &mut JobState,
656 backend: &Arc<dyn ExternalBackend>,
657 store: Option<&Arc<crate::store::TaskStore>>,
658 repo: &str,
659 transport: Option<&Arc<Transport>>,
660 base_dir: &Path,
661) {
662 match job.r#type.as_str() {
663 "task" => {
664 if let Some(ref template) = job.task {
665 let body = match resolve_template_body(template, base_dir) {
666 Ok(b) => b,
667 Err(e) => {
668 tracing::error!(job_id = job.id, ?e, "failed to resolve task body");
669 state.last_task_status = Some("failed".to_string());
670 return;
671 }
672 };
673
674 if job.external {
675 let mut labels = template.labels.clone();
676 labels.push("scheduled".to_string());
677 labels.push(format!("job:{}", job.id));
678
679 if let Some(ref agent) = template.agent
680 && !agent.is_empty()
681 {
682 labels.push(format!("agent:{agent}"));
683 }
684
685 match backend.create_task(&template.title, &body, &labels).await {
686 Ok(ext_id) => {
687 tracing::info!(
688 job_id = job.id,
689 task_id = ext_id.0,
690 "created external task"
691 );
692 state.active_task_id = Some(ext_id.0);
693 state.last_task_status = Some("new".to_string());
694 }
695 Err(e) => {
696 tracing::error!(job_id = job.id, ?e, "failed to create external task");
697 state.last_task_status = Some("failed".to_string());
698 }
699 }
700 } else if let Some(s) = store {
701 match s
702 .create_internal(repo, &template.title, &body, "cron", &job.id, None)
703 .await
704 {
705 Ok(internal_id) => {
706 let task_id = format!("internal:{internal_id}");
707 tracing::info!(job_id = job.id, task_id, "created internal task");
708 state.active_task_id = Some(task_id);
709 state.last_task_status = Some("new".to_string());
710 }
711 Err(e) => {
712 tracing::error!(job_id = job.id, ?e, "failed to create internal task");
713 state.last_task_status = Some("failed".to_string());
714 }
715 }
716 } else {
717 tracing::error!(
718 job_id = job.id,
719 "no store available for internal task creation"
720 );
721 state.last_task_status = Some("failed".to_string());
722 }
723 }
724 }
725 "bash" => {
726 if let Some(ref cmd) = job.command {
727 let dir = job.dir.as_deref().unwrap_or(".");
728 tracing::info!(job_id = job.id, cmd, dir, "running bash command");
729
730 let timeout_secs: u64 = crate::config::get("jobs.bash_timeout_seconds")
734 .ok()
735 .and_then(|s| s.parse().ok())
736 .unwrap_or(300);
737 let timeout = std::time::Duration::from_secs(timeout_secs);
738
739 let output = tokio::time::timeout(
740 timeout,
741 tokio::process::Command::new("bash")
742 .arg("-c")
743 .arg(cmd)
744 .current_dir(dir)
745 .output_with_context(),
746 )
747 .await;
748
749 match output {
750 Ok(Ok(o)) if o.status.success() => {
751 state.last_task_status = Some("done".to_string());
752 }
753 Ok(Ok(o)) => {
754 let stderr = String::from_utf8_lossy(&o.stderr);
755 tracing::warn!(
756 job_id = job.id,
757 code = o.status.code(),
758 %stderr,
759 "bash command failed"
760 );
761 state.last_task_status = Some("failed".to_string());
762 }
763 Ok(Err(e)) => {
764 tracing::error!(job_id = job.id, ?e, "bash command error");
765 state.last_task_status = Some("failed".to_string());
766 }
767 Err(_) => {
768 tracing::error!(
769 job_id = job.id,
770 secs = timeout_secs,
771 "bash job timed out after {}s — killing to unblock tick loop",
772 timeout_secs
773 );
774 state.last_task_status = Some("timeout".to_string());
775 }
776 }
777 }
778 }
779 other => {
785 tracing::warn!(job_id = job.id, r#type = other, "unknown job type");
786 }
787 }
788
789 if job.notify
791 && let Some(t) = transport
792 {
793 let status = state
794 .last_task_status
795 .as_deref()
796 .unwrap_or("unknown")
797 .to_string();
798 let summary = match status.as_str() {
799 "done" => format!("Job `{}` completed successfully.", job.id),
800 "failed" => format!("Job `{}` failed.", job.id),
801 "new" => format!("Job `{}` created a new task.", job.id),
802 other => format!("Job `{}` finished with status: {other}.", job.id),
803 };
804 let target = job
806 .notify_target
807 .clone()
808 .or_else(|| crate::config::get("channels.telegram.chat_id").ok());
809 let notification = TaskNotification {
810 task_id: job.id.clone(),
811 title: format!("Job: {}", job.id),
812 status,
813 agent: "scheduler".to_string(),
814 duration_seconds: 0.0,
815 summary,
816 repo: Some(repo.to_string()),
817 notify_target: target,
818 pr_number: None,
819 };
820 t.push_notification(notification);
821 }
822}
823
824#[cfg(test)]
829mod tests {
830 use super::*;
831 use std::fs;
832 use tempfile::tempdir;
833
834 fn write_config(dir: &Path, content: &str) -> PathBuf {
835 let path = dir.join(".orch.yml");
836 fs::write(&path, content).unwrap();
837 path
838 }
839
840 #[test]
841 fn load_jobs_reads_prompt_from_file() {
842 let tmp = tempdir().unwrap();
843 fs::create_dir(tmp.path().join("prompts")).unwrap();
844 fs::write(tmp.path().join("prompts/hello.md"), "hello from file").unwrap();
845 let cfg = write_config(
846 tmp.path(),
847 r#"
848jobs:
849 - id: with-prompt
850 schedule: "0 9 * * *"
851 task:
852 title: "Daily"
853 prompt: prompts/hello.md
854"#,
855 );
856
857 let jobs = load_jobs(&cfg).unwrap();
858 assert_eq!(jobs.len(), 1);
859 let body = resolve_template_body(jobs[0].task.as_ref().unwrap(), tmp.path()).unwrap();
860 assert_eq!(body, "hello from file");
861 }
862
863 #[test]
864 fn load_jobs_rejects_both_body_and_prompt() {
865 let tmp = tempdir().unwrap();
866 fs::write(tmp.path().join("p.md"), "x").unwrap();
867 let cfg = write_config(
868 tmp.path(),
869 r#"
870jobs:
871 - id: conflict
872 schedule: "0 9 * * *"
873 task:
874 title: "x"
875 body: "inline"
876 prompt: p.md
877"#,
878 );
879
880 let err = load_jobs(&cfg).unwrap_err().to_string();
881 assert!(err.contains("not both"), "unexpected error: {err}");
882 }
883
884 #[test]
885 fn load_jobs_rejects_missing_prompt_file() {
886 let tmp = tempdir().unwrap();
887 let cfg = write_config(
888 tmp.path(),
889 r#"
890jobs:
891 - id: missing
892 schedule: "0 9 * * *"
893 task:
894 title: "x"
895 prompt: does-not-exist.md
896"#,
897 );
898
899 let err = load_jobs(&cfg).unwrap_err().to_string();
900 assert!(
901 err.contains("prompt file not found"),
902 "unexpected error: {err}"
903 );
904 }
905
906 #[test]
907 fn resolve_template_body_falls_back_to_inline_body() {
908 let tmp = tempdir().unwrap();
909 let template = TaskTemplate {
910 title: "t".to_string(),
911 body: "inline body".to_string(),
912 prompt: None,
913 labels: vec![],
914 agent: None,
915 };
916 assert_eq!(
917 resolve_template_body(&template, tmp.path()).unwrap(),
918 "inline body"
919 );
920 }
921
922 fn write_prompt_job(dir: &Path, name: &str, content: &str) {
923 let jobs_dir = dir.join("prompts").join("jobs");
924 fs::create_dir_all(&jobs_dir).unwrap();
925 fs::write(jobs_dir.join(name), content).unwrap();
926 }
927
928 #[test]
929 fn scan_prompt_jobs_picks_up_frontmatter_files() {
930 let tmp = tempdir().unwrap();
931 write_prompt_job(
932 tmp.path(),
933 "morning.md",
934 "---\nid: morning\nschedule: '0 9 * * *'\ntitle: Morning\nlabels: [daily]\nagent: claude\n---\n\nDo morning stuff.\n",
935 );
936 let jobs = scan_prompt_jobs(tmp.path()).unwrap();
937 assert_eq!(jobs.len(), 1);
938 assert_eq!(jobs[0].id, "morning");
939 assert_eq!(jobs[0].schedule, "0 9 * * *");
940 let task = jobs[0].task.as_ref().unwrap();
941 assert_eq!(task.title, "Morning");
942 assert_eq!(task.body, "Do morning stuff.\n");
943 assert_eq!(task.labels, vec!["daily".to_string()]);
944 assert_eq!(task.agent.as_deref(), Some("claude"));
945 }
946
947 #[test]
948 fn load_jobs_merges_inline_and_scanned() {
949 let tmp = tempdir().unwrap();
950 write_prompt_job(
951 tmp.path(),
952 "scanned.md",
953 "---\nid: scanned\nschedule: '0 9 * * *'\ntitle: Scanned\n---\n\nbody\n",
954 );
955 let cfg = write_config(
956 tmp.path(),
957 r#"
958jobs:
959 - id: inline
960 schedule: "0 10 * * *"
961 task:
962 title: "Inline"
963 body: "x"
964"#,
965 );
966 let jobs = load_jobs(&cfg).unwrap();
967 let ids: Vec<&str> = jobs.iter().map(|j| j.id.as_str()).collect();
968 assert!(ids.contains(&"inline"));
969 assert!(ids.contains(&"scanned"));
970 assert_eq!(jobs.len(), 2);
971 }
972
973 #[test]
974 fn load_jobs_rejects_duplicate_id_across_sources() {
975 let tmp = tempdir().unwrap();
976 write_prompt_job(
977 tmp.path(),
978 "dup.md",
979 "---\nid: dup\nschedule: '0 9 * * *'\ntitle: Dup\n---\n\nbody\n",
980 );
981 let cfg = write_config(
982 tmp.path(),
983 r#"
984jobs:
985 - id: dup
986 schedule: "0 10 * * *"
987 task:
988 title: "Dup inline"
989 body: "x"
990"#,
991 );
992 let err = load_jobs(&cfg).unwrap_err().to_string();
993 assert!(err.contains("duplicate job id"), "unexpected error: {err}");
994 }
995
996 #[test]
997 fn scan_prompt_jobs_ignores_files_without_frontmatter() {
998 let tmp = tempdir().unwrap();
999 write_prompt_job(
1000 tmp.path(),
1001 "plain.md",
1002 "just a prompt body, no frontmatter\n",
1003 );
1004 let jobs = scan_prompt_jobs(tmp.path()).unwrap();
1005 assert_eq!(jobs.len(), 0);
1006 }
1007
1008 #[test]
1009 fn load_jobs_works_without_config_file_when_directory_present() {
1010 let tmp = tempdir().unwrap();
1011 write_prompt_job(
1012 tmp.path(),
1013 "solo.md",
1014 "---\nid: solo\nschedule: '0 9 * * *'\ntitle: Solo\n---\n\nbody\n",
1015 );
1016 let missing_cfg = tmp.path().join(".orch.yml");
1017 let jobs = load_jobs(&missing_cfg).unwrap();
1018 assert_eq!(jobs.len(), 1);
1019 assert_eq!(jobs[0].id, "solo");
1020 }
1021
1022 #[test]
1025 fn scan_prompt_jobs_respects_enabled_false() {
1026 let tmp = tempdir().unwrap();
1027 write_prompt_job(
1028 tmp.path(),
1029 "disabled.md",
1030 "---\nid: disabled\nschedule: '0 9 * * *'\ntitle: Disabled\nenabled: false\n---\n\nbody\n",
1031 );
1032 let jobs = scan_prompt_jobs(tmp.path()).unwrap();
1033 assert_eq!(jobs.len(), 1);
1034 assert!(!jobs[0].enabled, "job should be disabled via frontmatter");
1035 }
1036
1037 #[test]
1038 fn scan_prompt_jobs_sets_prompt_file() {
1039 let tmp = tempdir().unwrap();
1040 write_prompt_job(
1041 tmp.path(),
1042 "morning.md",
1043 "---\nid: morning\nschedule: '0 9 * * *'\ntitle: Morning\n---\n\nbody\n",
1044 );
1045 let jobs = scan_prompt_jobs(tmp.path()).unwrap();
1046 assert_eq!(jobs.len(), 1);
1047 assert!(
1048 jobs[0].prompt_file.is_some(),
1049 "prompt_file should be set for frontmatter jobs"
1050 );
1051 }
1052
1053 #[test]
1054 fn save_jobs_does_not_persist_prompt_based_jobs() {
1055 let tmp = tempdir().unwrap();
1056 write_prompt_job(
1058 tmp.path(),
1059 "prompt.md",
1060 "---\nid: from-prompt\nschedule: '0 9 * * *'\ntitle: Prompt Job\n---\n\nbody\n",
1061 );
1062 let cfg = write_config(
1064 tmp.path(),
1065 "jobs:\n - id: inline\n schedule: \"0 10 * * *\"\n task:\n title: Inline\n body: x\n",
1066 );
1067 let jobs = load_jobs(&cfg).unwrap();
1068 assert_eq!(jobs.len(), 2);
1069
1070 save_jobs(&cfg, &jobs).unwrap();
1072
1073 let saved = load_jobs(&cfg).unwrap();
1074 assert_eq!(saved.len(), 2, "both jobs should still be loadable");
1075 let ids: Vec<&str> = saved.iter().map(|j| j.id.as_str()).collect();
1076 assert!(ids.contains(&"inline"));
1077 assert!(ids.contains(&"from-prompt"));
1078 }
1079
1080 #[test]
1081 fn rewrite_frontmatter_enabled_replaces_existing_value() {
1082 let input = "---\nid: foo\nschedule: daily\nenabled: true\ntitle: Foo\n---\n\nbody\n";
1083 let out = rewrite_frontmatter_enabled(input, "false");
1084 assert!(
1085 out.contains("enabled: false"),
1086 "should replace enabled: true"
1087 );
1088 assert!(!out.contains("enabled: true"), "old value must be gone");
1089 assert!(out.contains("body"), "body must be preserved");
1090 }
1091
1092 #[test]
1093 fn rewrite_frontmatter_enabled_inserts_when_absent() {
1094 let input = "---\nid: foo\nschedule: daily\ntitle: Foo\n---\n\nbody\n";
1095 let out = rewrite_frontmatter_enabled(input, "false");
1096 assert!(
1097 out.contains("enabled: false"),
1098 "should insert enabled: false"
1099 );
1100 assert!(out.contains("body"), "body must be preserved");
1101 }
1102
1103 #[test]
1104 fn set_frontmatter_enabled_writes_file() {
1105 let tmp = tempdir().unwrap();
1106 let path = tmp.path().join("job.md");
1107 fs::write(
1108 &path,
1109 "---\nid: foo\nschedule: daily\ntitle: Foo\nenabled: true\n---\n\nbody\n",
1110 )
1111 .unwrap();
1112 set_frontmatter_enabled(&path, false).unwrap();
1113 let content = fs::read_to_string(&path).unwrap();
1114 assert!(content.contains("enabled: false"));
1115 assert!(!content.contains("enabled: true"));
1116 }
1117}