1pub mod escalate;
8pub mod events;
9pub mod integrate;
10pub mod lease;
11pub mod mainline;
12pub mod progress;
13pub mod retry;
14mod sched;
15pub mod worker;
16
17use std::path::{Path, PathBuf};
18
19use vitrify_core::config::{Config, Overrides};
20use vitrify_core::harness::Role;
21use vitrify_core::model::{self, Instance, Shape, UtcTime};
22use vitrify_core::{CoreError, audit};
23
24use crate::cmd;
25use crate::gate::MemoRunner;
26use crate::git::{Git, resolve_mainline, use_push};
27use crate::home;
28use crate::layout::{self, Layout};
29use crate::out::{J, diag, emit};
30use crate::signals;
31use mainline::Mainline;
32
33pub struct RunFlags {
34 pub dry_run: bool,
35 pub cap: Option<i64>,
36 pub sdd: Option<String>,
37 pub mainline: Option<String>,
38 pub gate_jobs: Option<i64>,
40 pub wait: bool,
43}
44
45pub(crate) struct Ctx {
46 pub ml: Mainline,
48 pub cfg: Config,
49 pub cap: usize,
50 pub home: PathBuf,
51 pub harness: String,
52 pub argv: Vec<String>,
54 pub worker_argv: Vec<String>,
56 pub retry_argv: Vec<String>,
59 pub escalation_argv: Vec<String>,
61 pub roles: Vec<String>,
63 pub profile_error: Option<String>,
66 pub sdd_arg: Option<String>,
67 pub job_id: String,
68 pub logs_dir: PathBuf,
69 pub wait: bool,
70 pub slug: String,
72 pub audited_at: Option<String>,
75}
76
77pub(crate) const VERSION: &str = env!("CARGO_PKG_VERSION");
78
79pub fn run(flags: RunFlags) -> Result<u8, CoreError> {
80 let here = Git::new(cmd::cwd());
81 let root = here.primary_root().map_err(CoreError::from)?;
82 let primary = Git::new(&root);
83 let cfg = cmd::load_config(&Overrides {
84 mainline: flags.mainline.clone(),
85 gate_jobs: flags.gate_jobs,
86 ..Default::default()
87 })?;
88 let mainline = resolve_mainline(&primary, flags.mainline.as_deref(), &cfg.mainline)
89 .map_err(CoreError::from)?;
90 let push = use_push(&primary, &mainline).map_err(CoreError::from)?;
91 let Some(home) = cmd::home_dir() else {
92 return Err(CoreError::refusal(
93 1,
94 "error: cannot resolve the vitrify home (set VITRIFY_HOME or HOME)",
95 ));
96 };
97 home::require_set_up(&home)?;
100 let layout = Layout::resolve(&root, Some(&home), &cfg.run.worktree_dir)?;
101
102 let (harness, argv) = select_harness(&home, &cfg);
105 let harness = harness.unwrap_or_default();
106 let argv = argv.unwrap_or_default();
107 let (worker_argv, retry_argv, escalation_argv, roles, profile_error) =
110 match cmd::probe::role_profiles(&home, Some(&root)) {
111 Ok(profiles) => {
112 let profile = profiles.get(&harness);
113 (
114 profiles.argv_for(&harness, &argv, Role::Worker),
115 profiles.argv_for(&harness, &argv, Role::Retry),
116 profiles.argv_for(&harness, &argv, Role::Escalation),
117 Role::ALL
118 .iter()
119 .filter(|r| profile.is_own(**r))
120 .map(|r| format!("{} {}", r.as_str(), profile.describe(*r)))
121 .collect(),
122 None,
123 )
124 }
125 Err(e) => (
126 argv.clone(),
127 argv.clone(),
128 argv.clone(),
129 Vec::new(),
130 Some(e.to_string()),
131 ),
132 };
133
134 let now = UtcTime::now();
135 let job_id = format!(
136 "run-{}-p{}",
137 now.format().replace(['-', ':'], ""),
138 std::process::id()
139 );
140 let logs_dir = layout.scratch.join("logs").join(&job_id);
141
142 let mut ctx = Ctx {
143 ml: Mainline {
144 primary,
145 layout,
146 sdd_rel: PathBuf::new(),
147 branch: mainline,
148 push,
149 },
150 cap: flags.cap.unwrap_or(cfg.run.worker_cap).max(1) as usize,
151 cfg,
152 home,
153 harness,
154 argv,
155 worker_argv,
156 retry_argv,
157 escalation_argv,
158 roles,
159 profile_error,
160 sdd_arg: flags.sdd.clone(),
161 job_id,
162 logs_dir,
163 wait: flags.wait,
164 slug: String::new(),
165 audited_at: None,
166 };
167
168 signals::install();
172 crate::cmd::claim::quiet_resync(true);
173
174 let behind = if flags.dry_run {
178 crate::cmd::claim::behind_note(&ctx.ml.primary, &ctx.ml.branch)
179 } else {
180 let _turn = crate::cmd::claim::tx_lock();
181 crate::cmd::claim::catch_up_primary(&ctx.ml.primary, &ctx.ml.branch)
182 };
183 if let Some(note) = behind {
184 diag(¬e);
185 }
186
187 let mut failures: Vec<String> = Vec::new();
189 let inst = preflight(&mut ctx, &mut failures, flags.dry_run)?;
190 if let Some(sig) = signals::pending() {
191 diag(&format!(
192 "interrupted ({}) during preflight",
193 signals::name(sig)
194 ));
195 signals::die_by(sig);
196 }
197 let inst = match inst {
198 Some(inst) => inst,
199 None => {
200 for fail in &failures {
201 diag(&format!("preflight failed: {fail}"));
202 }
203 return Ok(2);
204 }
205 };
206
207 print_header(&ctx, &inst, !flags.dry_run);
209 if flags.dry_run {
210 for line in sched::dead_run_notes(&ctx, &inst) {
211 emit(&line);
212 }
213 emit("dry-run: preflight green; stopping before dispatch");
214 emit(&format!("Start: {}", start_command(&flags)));
215 return Ok(0);
216 }
217
218 sched::orchestrate(ctx)
219}
220
221fn start_command(flags: &RunFlags) -> String {
224 let mut words = vec!["vitrify".to_string(), "run".to_string()];
225 if let Some(cap) = flags.cap {
226 words.extend(["--cap".to_string(), cap.to_string()]);
227 }
228 if let Some(jobs) = flags.gate_jobs {
229 words.extend(["--gate-jobs".to_string(), jobs.to_string()]);
230 }
231 if flags.wait {
232 words.push("--wait".to_string());
233 }
234 if let Some(sdd) = &flags.sdd {
235 words.extend(["--sdd".to_string(), shell_word(sdd)]);
236 }
237 if let Some(branch) = &flags.mainline {
238 words.extend(["--mainline".to_string(), shell_word(branch)]);
239 }
240 words.join(" ")
241}
242
243pub(crate) fn shell_word(s: &str) -> String {
246 let plain = !s.is_empty()
247 && s.chars()
248 .all(|c| c.is_ascii_alphanumeric() || "-_./:@+=,%".contains(c));
249 if plain {
250 s.to_string()
251 } else {
252 format!("'{}'", s.replace('\'', "'\\''"))
253 }
254}
255
256fn with_fix(cause: &str, fix: &str) -> String {
259 let cause = cause.strip_prefix("error: ").unwrap_or(cause);
260 match cause.split_once('\n') {
261 Some((first, rest)) => format!("{first} → {fix}\n{rest}"),
262 None => format!("{cause} → {fix}"),
263 }
264}
265
266fn sdd_failure(cause: &str) -> String {
270 let cause = cause.strip_prefix("error: ").unwrap_or(cause);
271 let first = cause.lines().next().unwrap_or_default();
272 if first.contains(" → ") {
273 return cause.to_string();
274 }
275 let fix = if cause.contains("no SDD found") {
276 "vitrify brief authoring"
277 } else if cause.contains("multiple SDDs") || cause.contains("several SDDs") {
278 "pass one of these --sdd values"
279 } else {
280 "vitrify locate"
281 };
282 match first.strip_suffix(':') {
283 Some(lead) => format!("{lead} → {fix}:{}", &cause[first.len()..]),
284 None => with_fix(cause, fix),
285 }
286}
287
288fn select_harness(home: &Path, cfg: &Config) -> (Option<String>, Option<Vec<String>>) {
289 let order: Vec<&str> = if cfg.harness.preferred.is_empty() {
290 vec!["claude", "codex", "opencode"]
291 } else {
292 vec![cfg.harness.preferred.as_str()]
293 };
294 for name in order {
295 if let Some(argv) = cmd::probe::recorded_headless(home, name) {
296 return (Some(name.to_string()), Some(argv));
297 }
298 }
299 (None, None)
300}
301
302fn preflight(
303 ctx: &mut Ctx,
304 failures: &mut Vec<String>,
305 dry_run: bool,
306) -> Result<Option<Instance>, CoreError> {
307 let root = ctx.ml.primary.dir.clone();
308 let located = match ctx.sdd_arg.as_deref() {
312 Some(arg) => {
313 let here = cmd::repo_root();
314 cmd::resolve_sdd(&here, Some(arg), &cmd::cwd()).map(|h| {
315 cmd::sdd_rel(&here, &h.root)
316 .or_else(|| cmd::sdd_rel(&root, &h.root))
317 .ok_or(h.root)
318 })
319 }
320 None => cmd::resolve_sdd(&root, None, &cmd::cwd())
321 .map(|h| cmd::sdd_rel(&root, &h.root).ok_or(h.root)),
322 };
323 let sdd_rel = match located {
326 Ok(Ok(rel)) => rel,
327 Ok(Err(outside)) => {
328 failures.push(with_fix(
329 &format!(
330 "SDD {} is outside the repository {}",
331 outside.display(),
332 root.display()
333 ),
334 "pass an --sdd inside this repository",
335 ));
336 return Ok(None);
337 }
338 Err(e) => {
339 failures.push(sdd_failure(&e.to_string()));
340 return Ok(None);
341 }
342 };
343 let inst = match cmd::resolve_sdd_in(&root, &sdd_rel).and_then(Instance::load) {
345 Ok(inst) => inst,
346 Err(e) => {
347 failures.push(sdd_failure(&e.to_string()));
348 return Ok(None);
349 }
350 };
351 ctx.ml.sdd_rel = sdd_rel;
352 ctx.slug = layout::sdd_slug(&inst);
353
354 let sdd_word = shell_word(&cmd::sdd_arg(&ctx.ml.sdd_rel));
355 if inst.meta.get_str_or("status", "Draft") != "Active" {
356 failures.push(with_fix(
357 &format!(
358 "SDD status is {}, not Active",
359 inst.meta.get_str_or("status", "Draft")
360 ),
361 "finish authoring and set it Active: vitrify brief authoring",
362 ));
363 }
364 let porcelain = ctx.ml.primary.status_porcelain().map_err(CoreError::from)?;
366 let spec_rel = cmd::sdd_arg(&ctx.ml.sdd_rel);
367 let under_spec =
368 |p: &str| spec_rel == "." || p == spec_rel || p.starts_with(&format!("{spec_rel}/"));
369 let dirty_spec: Vec<&str> = porcelain
370 .lines()
371 .filter(|l| l.split_whitespace().nth(1).is_some_and(under_spec))
372 .collect();
373 if !dirty_spec.is_empty() {
374 if crate::cmd::claim::behind_note(&ctx.ml.primary, &ctx.ml.branch).is_some() {
375 failures.push(with_fix(
377 &format!(
378 "the primary checkout is behind {} — its copy of the SDD is not the one at the mainline head",
379 ctx.ml.branch
380 ),
381 "bring it up to date as the note above says",
382 ));
383 } else {
384 failures.push(with_fix(
385 &format!(
386 "SDD not committed at the mainline head (uncommitted spec changes): {}",
387 dirty_spec.join("; ")
388 ),
389 &format!("commit or stash the changes under {sdd_word}"),
390 ));
391 }
392 }
393 if ctx.ml.push {
398 let _ = ctx.ml.primary.fetch_origin(&ctx.ml.branch);
399 let local = ctx
400 .ml
401 .primary
402 .rev_parse(&format!("refs/heads/{}", ctx.ml.branch));
403 let remote = ctx
404 .ml
405 .primary
406 .rev_parse(&format!("refs/remotes/origin/{}", ctx.ml.branch));
407 if let (Ok(local), Ok(remote)) = (local, remote)
408 && local != remote
409 && !ctx.ml.primary.is_ancestor(&local, &remote).unwrap_or(false)
410 {
411 failures.push(with_fix(
412 &format!(
413 "the local {b} holds commits origin/{b} does not — the run builds origin's head, so they would be left out",
414 b = ctx.ml.branch
415 ),
416 &format!("publish them first: git push origin {}", shell_word(&ctx.ml.branch)),
417 ));
418 }
419 }
420 for other in cmd::discover(&root) {
422 if other.root != inst.root
423 && layout::slug_of(&other.meta, &other.root, other.shape) == ctx.slug
424 {
425 failures.push(with_fix(
426 &format!(
427 "SDD slug `{}` is also used by {} — branch and worktree names would collide",
428 ctx.slug,
429 other.root.display()
430 ),
431 "rename one of the `sdd:` slugs",
432 ));
433 }
434 }
435
436 let lint_findings =
439 cmd::lint::pre_run_findings(&inst, &root, ctx.cfg.lint.readset_budget_bytes)?;
440 for x in &lint_findings {
441 failures.push(with_fix(
442 &format!("lint [{}] {}: {}", x.check, x.subject, x.cause),
443 &x.remediation,
444 ));
445 }
446
447 let jobs = ctx.cfg.run.rows_at_once();
451 let runner = MemoRunner::for_verified(&inst, &root, jobs)?;
452 let (findings, _) = audit::run(
453 &inst,
454 &root,
455 &cmd::audit_options(audit::Options::default(), &root, &inst),
456 &runner,
457 UtcTime::now(),
458 )?;
459 if signals::interrupted() {
460 return Ok(None);
461 }
462 let audit_clean = findings.is_empty();
463 if !audit_clean {
464 if findings.iter().all(|f| f.check == 7) {
465 if dry_run {
466 diag(&format!(
468 "preflight: {} lapsed lease(s) — a run releases them before it starts",
469 findings.len()
470 ));
471 } else {
472 ctx.ml.heal(true, false)?;
473 diag(&format!(
474 "preflight: {} lapsed lease(s) fixed and published",
475 findings.len()
476 ));
477 }
478 } else {
479 for f in &findings {
480 failures.push(with_fix(
481 &format!("audit [check {}] {}: {}", f.check, f.subject, f.cause),
482 &f.remediation,
483 ));
484 }
485 }
486 }
487
488 let core_text = model::read_text(&inst.file)?;
493 let cmds = integrate::sdd_commands(&core_text);
494 for (name, cmd_opt) in [
495 ("bootstrap", &cmds.bootstrap),
496 ("build", &cmds.build),
497 ("lint", &cmds.lint),
498 ] {
499 match cmd_opt {
500 Some(c) => {
501 let (ok, output) = integrate::run_gate_command(c, &root);
502 if signals::interrupted() {
503 return Ok(None);
504 }
505 if !ok {
506 let quoted = tail(&output, 5);
507 let cause = format!("§5 {name} command failed: {c}");
508 let fix = "run it from the repository root and fix what it reports";
509 failures.push(if quoted.is_empty() {
510 with_fix(&cause, fix)
511 } else {
512 format!("{}\n{quoted}", with_fix(&cause, fix))
513 });
514 }
515 }
516 None => failures.push(with_fix(
517 &format!("§5 Commands block missing the {name} command"),
518 &format!("add the {name} command to the SDD's §5 Commands"),
519 )),
520 }
521 }
522
523 if ctx.argv.is_empty() {
525 failures.push(with_fix(
526 "~/.vitrify/config.toml records no working harness",
527 "vitrify probe",
528 ));
529 }
530 if let Some(e) = &ctx.profile_error {
531 failures.push(with_fix(
532 e,
533 "correct the line the error names, then vitrify probe",
534 ));
535 }
536
537 if let Err(e) = ctx.ml.layout.ensure_worktree_root(&ctx.ml.primary) {
539 failures.push(with_fix(
540 &e.to_string(),
541 "point run.worktree_dir at a directory no ignore file of the repository covers",
542 ));
543 }
544
545 if inst.shape == Shape::Single && ctx.cap > 1 {
547 diag("note: single-file SDD — worker cap forced to 1 (every status edit shares one file)");
548 ctx.cap = 1;
549 }
550
551 if audit_clean
554 && failures.is_empty()
555 && let Ok(head) = ctx.ml.head()
556 && ctx.ml.primary.rev_parse("HEAD").ok().as_deref() == Some(head.as_str())
557 && ctx.ml.primary.clean_against(&head).unwrap_or(false)
558 {
559 ctx.audited_at = Some(head);
560 }
561
562 if failures.is_empty() {
563 Ok(Some(inst))
564 } else {
565 Ok(None)
566 }
567}
568
569pub(crate) fn tail(text: &str, n: usize) -> String {
572 let lines: Vec<&str> = text.lines().filter(|l| !l.trim().is_empty()).collect();
573 let start = lines.len().saturating_sub(n);
574 lines[start..].join("\n")
575}
576
577fn print_header(ctx: &Ctx, inst: &Instance, watch: bool) {
580 let slug = inst.meta.get_str_or("sdd", "?");
581 let version = inst.meta.get_str_or("version", "?");
582 emit(&format!(
583 "SDD build job — {slug} @ {version} [{}]",
584 ctx.job_id
585 ));
586 let has_test = model::read_text(&inst.file)
587 .map(|text| integrate::sdd_commands(&text).test.is_some())
588 .unwrap_or(false);
589 emit(&format!(
590 "Done-condition: every non-Retired unit Verified @ {version}; audit clean; replay clean{}",
591 if has_test { "; §5 Test passing" } else { "" }
592 ));
593 emit(&format!(
594 "Mainline: {} Remote: {} Shape: {}",
595 ctx.ml.branch,
596 if ctx.ml.push { "origin" } else { "none" },
597 inst.shape.as_str()
598 ));
599 emit(&format!("Plan: {}", plan(inst)));
600 emit(&format!(
601 "Workers: cap={} Holder IDs: {}-w<i> Harness: {}",
602 ctx.cap,
603 ctx.job_id,
604 if ctx.harness.is_empty() {
605 "-"
606 } else {
607 &ctx.harness
608 }
609 ));
610 if !ctx.roles.is_empty() && !ctx.harness.is_empty() {
611 emit(&format!("Roles: {}", ctx.roles.join(" ")));
612 }
613 emit(&format!(
614 "Worktrees: {} Branches: sdd/{}/<unit>/c<seq>",
615 ctx.ml.layout.wt_root.display(),
616 ctx.slug
617 ));
618 emit(&format!(
619 "Parameters: worker cap {} · gate jobs {}{} · lease {}m · renew at {} remaining · escalate after {} failed attempts of a unit, set it aside after {}",
620 ctx.cap,
621 ctx.cfg.run.rows_at_once(),
622 if ctx.cfg.run.rows_follow_cores() {
623 " (one per core)"
624 } else {
625 ""
626 },
627 ctx.cfg.run.lease_minutes,
628 ctx.cfg.run.renew_fraction,
629 ctx.cfg.run.abort_failed_waves.max(1),
630 ctx.cfg.run.abort_failed_waves.max(1) * 2
631 ));
632 if watch {
633 emit(&format!(
634 "Watch: vitrify run status --job {} [--follow] · once it ends, the same command prints the report · procedure: vitrify brief run",
635 ctx.job_id
636 ));
637 }
638}
639
640fn plan(inst: &Instance) -> String {
644 let mut parts: Vec<String> = Vec::new();
645 let mut units: Vec<&model::Unit> = inst.units.iter().collect();
646 units.sort_by(|a, b| a.unit.cmp(&b.unit));
647 let mut seen_groups: Vec<String> = Vec::new();
648 for u in &units {
649 let status = u.meta.get_str_or("status", "Draft");
650 let group = u.meta.get_str_or("parallel_group", "").trim().to_string();
651 if model::is_empty_marker(&group) {
652 parts.push(format!("{} ({status})", u.unit));
653 } else if !seen_groups.contains(&group) {
654 seen_groups.push(group.clone());
655 let members: Vec<String> = units
656 .iter()
657 .filter(|x| x.meta.get_str_or("parallel_group", "").trim() == group)
658 .map(|x| x.unit.clone())
659 .collect();
660 parts.push(format!("[P:{group}] {}", members.join(", ")));
661 }
662 }
663 parts.join(" → ")
664}
665
666pub(crate) struct WorkerRec {
670 pub holder: String,
671 pub pid: u32,
672 pub unit: String,
673 pub claim_seq: i64,
674 pub branch: String,
675 pub worktree: String,
676 pub started_at: String,
677 pub ended_at: Option<String>,
678 pub outcome: String,
680 pub retry: bool,
683 pub detail: Option<String>,
686}
687
688#[derive(Default)]
689pub(crate) struct RunState {
690 pub workers: Vec<WorkerRec>,
691 pub reports: Vec<String>,
692 pub escalations: Vec<(String, String)>, pub gate_failures: Vec<(String, String, String)>, pub attempts: Vec<(String, String, String)>, pub report: Option<Vec<String>>,
698}
699
700pub(crate) fn write_run_json(
705 ctx: &Ctx,
706 state: &RunState,
707 started_at: &str,
708 terminated: Option<(&str, &str)>,
709) -> Result<(), CoreError> {
710 let workers: Vec<J> = state
711 .workers
712 .iter()
713 .map(|w| {
714 J::Obj(vec![
715 ("holder".into(), J::s(w.holder.clone())),
716 ("pid".into(), J::Int(w.pid as i64)),
717 ("unit".into(), J::s(w.unit.clone())),
718 ("claim_seq".into(), J::Int(w.claim_seq)),
719 ("branch".into(), J::s(w.branch.clone())),
720 ("worktree".into(), J::s(w.worktree.clone())),
721 ("started_at".into(), J::s(w.started_at.clone())),
722 ("ended_at".into(), J::opt_str(w.ended_at.clone())),
723 ("outcome".into(), J::s(w.outcome.clone())),
724 ("retry".into(), J::Bool(w.retry)),
725 ("detail".into(), J::opt_str(w.detail.clone())),
726 ])
727 })
728 .collect();
729 let escalations: Vec<J> = state
730 .escalations
731 .iter()
732 .map(|(p, v)| {
733 J::Obj(vec![
734 ("evidence_path".into(), J::s(p.clone())),
735 ("verdict".into(), J::s(v.clone())),
736 ])
737 })
738 .collect();
739 let mut pairs = vec![
740 ("job_id".into(), J::s(ctx.job_id.clone())),
741 ("pid".into(), J::Int(std::process::id() as i64)),
742 ("sdd".into(), J::s(cmd::sdd_arg(&ctx.ml.sdd_rel))),
743 ("harness".into(), J::s(ctx.harness.clone())),
744 ("started_at".into(), J::s(started_at)),
745 (
746 "done_condition".into(),
747 J::s(
748 "every non-Retired unit Verified @ current SDD version; audit clean; replay clean; §5 Test passing (when the SDD has one)",
749 ),
750 ),
751 (
752 "params".into(),
753 J::Obj(vec![
754 ("cap".into(), J::Int(ctx.cap as i64)),
755 (
756 "gate_jobs".into(),
757 J::Int(ctx.cfg.run.rows_at_once() as i64),
758 ),
759 ("lease_minutes".into(), J::Int(ctx.cfg.run.lease_minutes)),
760 (
761 "worker_timeout_minutes".into(),
762 J::Int(ctx.cfg.run.worker_timeout_minutes),
763 ),
764 (
765 "abort_failed_waves".into(),
766 J::Int(ctx.cfg.run.abort_failed_waves),
767 ),
768 ]),
769 ),
770 (
771 "worktrees".into(),
772 J::s(ctx.ml.layout.wt_root.display().to_string()),
773 ),
774 ("workers".into(), J::Arr(workers)),
775 (
776 "reports".into(),
777 J::Arr(state.reports.iter().map(|r| J::s(r.clone())).collect()),
778 ),
779 ("escalations".into(), J::Arr(escalations)),
780 ];
781 if let Some((end_state, detail)) = terminated {
782 pairs.push((
783 "terminated".into(),
784 J::Obj(vec![
785 ("state".into(), J::s(end_state)),
786 ("at".into(), J::s(UtcTime::now().format())),
787 ("detail".into(), J::s(detail)),
788 ]),
789 ));
790 }
791 pairs.push((
792 "report".into(),
793 state.report.as_ref().map_or(J::Null, |lines| {
794 J::Arr(lines.iter().map(|l| J::s(l.clone())).collect())
795 }),
796 ));
797 let body = J::Obj(pairs).dumps_indent2();
798 ctx.ml.layout.ensure_scratch()?;
799 for dir in [ctx.ml.layout.scratch.clone(), ctx.logs_dir.clone()] {
800 std::fs::create_dir_all(&dir).map_err(|source| CoreError::Io {
801 path: dir.clone(),
802 source,
803 })?;
804 let path = dir.join("run.json");
805 let tmp = dir.join("run.json.tmp");
806 std::fs::write(&tmp, &body).map_err(|source| CoreError::Io {
807 path: tmp.clone(),
808 source,
809 })?;
810 std::fs::rename(&tmp, &path).map_err(|source| CoreError::Io { path, source })?;
811 }
812 Ok(())
813}