1pub mod escalate;
19pub mod events;
20pub mod history;
21pub mod integrate;
22mod lane;
23pub mod lease;
24pub mod mainline;
25mod plan;
26pub mod pool;
27pub mod progress;
28pub mod project;
29pub mod retry;
30mod sched;
31pub mod worker;
32
33use std::path::{Path, PathBuf};
34
35use vitrify_core::config::{Config, Overrides};
36use vitrify_core::harness::Role;
37use vitrify_core::model::{self, Instance, Shape, UtcTime};
38use vitrify_core::{CoreError, audit};
39
40use crate::cmd;
41use crate::gate::{self, ShRunner};
42use crate::git::{Git, resolve_mainline, use_push};
43use crate::home;
44use crate::incremental::dirty::{Cascade, Mode, Snapshot};
45use crate::incremental::recheck;
46use crate::layout::{self, Layout};
47use crate::out::{J, diag, emit};
48use crate::signals;
49use integrate::RottenRow;
50use mainline::Mainline;
51use pool::Pool;
52
53pub struct RunFlags {
54 pub dry_run: bool,
55 pub cap: Option<i64>,
56 pub sdd: Option<String>,
57 pub mainline: Option<String>,
58 pub gate_jobs: Option<i64>,
60 pub wait: bool,
63 pub recheck: bool,
67 pub upstream: bool,
69}
70
71pub(crate) struct Ctx {
74 pub primary: Git,
76 pub layout: Layout,
77 pub branch: String,
79 pub push: bool,
81 pub cfg: Config,
82 pub cap: usize,
84 pub gate_pool: &'static Pool,
87 pub home: PathBuf,
88 pub harness: String,
89 pub argv: Vec<String>,
91 pub worker_argv: Vec<String>,
93 pub retry_argv: Vec<String>,
96 pub escalation_argv: Vec<String>,
98 pub roles: Vec<String>,
100 pub profile_error: Option<String>,
103 pub sdd_arg: Option<String>,
104 pub job_id: String,
105 pub logs_dir: PathBuf,
107 pub wait: bool,
108 pub recheck: bool,
111 pub upstream: bool,
113 pub project: bool,
117}
118
119impl Ctx {
120 pub fn mainline_for(&self, sdd_rel: PathBuf, slug: String) -> Mainline {
123 Mainline {
124 primary: self.primary.clone(),
125 layout: self.layout.clone(),
126 sdd_rel,
127 slug,
128 branch: self.branch.clone(),
129 push: self.push,
130 }
131 }
132}
133
134pub(crate) struct LaneSeed {
136 pub ml: Mainline,
138 pub inst: Instance,
140 pub cap: usize,
143 pub rotten: Vec<RottenRow>,
146 pub blocked: Vec<String>,
149 pub checked: Vec<String>,
152 pub suite_ran: bool,
153}
154
155pub(crate) const VERSION: &str = env!("CARGO_PKG_VERSION");
156
157pub fn run(flags: RunFlags) -> Result<u8, CoreError> {
158 let here = Git::new(cmd::cwd());
159 let root = here.primary_root().map_err(CoreError::from)?;
160 let primary = Git::new(&root);
161 let cfg = cmd::load_config(&Overrides {
162 mainline: flags.mainline.clone(),
163 gate_jobs: flags.gate_jobs,
164 ..Default::default()
165 })?;
166 let mainline = resolve_mainline(&primary, flags.mainline.as_deref(), &cfg.mainline)
167 .map_err(CoreError::from)?;
168 let push = use_push(&primary, &mainline).map_err(CoreError::from)?;
169 let Some(home) = cmd::home_dir() else {
170 return Err(CoreError::refusal(
171 1,
172 "error: cannot resolve the vitrify home (set VITRIFY_HOME or HOME)",
173 ));
174 };
175 home::require_set_up(&home)?;
178 let layout = Layout::resolve(&root, Some(&home), &cfg.run.worktree_dir)?;
179
180 let (harness, argv) = select_harness(&home, &cfg);
183 let harness = harness.unwrap_or_default();
184 let argv = argv.unwrap_or_default();
185 let (worker_argv, retry_argv, escalation_argv, roles, profile_error) =
188 match cmd::probe::role_profiles(&home, Some(&root)) {
189 Ok(profiles) => {
190 let profile = profiles.get(&harness);
191 (
192 profiles.argv_for(&harness, &argv, Role::Worker),
193 profiles.argv_for(&harness, &argv, Role::Retry),
194 profiles.argv_for(&harness, &argv, Role::Escalation),
195 Role::ALL
196 .iter()
197 .filter(|r| profile.is_own(**r))
198 .map(|r| format!("{} {}", r.as_str(), profile.describe(*r)))
199 .collect(),
200 None,
201 )
202 }
203 Err(e) => (
204 argv.clone(),
205 argv.clone(),
206 argv.clone(),
207 Vec::new(),
208 Some(e.to_string()),
209 ),
210 };
211
212 let now = UtcTime::now();
213 let job_id = format!(
214 "run-{}-p{}",
215 now.format().replace(['-', ':'], ""),
216 std::process::id()
217 );
218 let logs_dir = layout.job_logs(&job_id);
219 let gate_pool = gate::install_pool(cfg.run.rows_at_once());
221
222 let mut ctx = Ctx {
223 primary,
224 layout,
225 branch: mainline,
226 push,
227 cap: flags.cap.unwrap_or(cfg.run.worker_cap).max(1) as usize,
228 gate_pool,
229 cfg,
230 home,
231 harness,
232 argv,
233 worker_argv,
234 retry_argv,
235 escalation_argv,
236 roles,
237 profile_error,
238 sdd_arg: flags.sdd.clone(),
239 job_id,
240 logs_dir,
241 wait: flags.wait,
242 recheck: flags.recheck,
243 upstream: flags.upstream,
244 project: false,
245 };
246
247 signals::install();
251 crate::cmd::claim::quiet_resync(true);
252
253 let behind = if flags.dry_run {
257 crate::cmd::claim::behind_note(&ctx.primary, &ctx.branch)
258 } else {
259 let _turn = crate::cmd::claim::tx_lock();
260 crate::cmd::claim::catch_up_primary(&ctx.primary, &ctx.branch)
261 };
262 if let Some(note) = behind {
263 diag(¬e);
264 }
265
266 let mut failures: Vec<String> = Vec::new();
268 let lanes = preflight(&mut ctx, &mut failures, flags.dry_run)?;
269 if let Some(sig) = signals::pending() {
270 diag(&format!(
271 "interrupted ({}) during preflight",
272 signals::name(sig)
273 ));
274 signals::die_by(sig);
275 }
276 let lanes = match lanes {
277 Ok(lanes) => lanes,
278 Err(code) => {
279 for fail in &failures {
280 diag(&format!("preflight failed: {fail}"));
281 }
282 return Ok(code);
283 }
284 };
285
286 let plan = plan::build(
290 &ctx,
291 &lanes,
292 if flags.dry_run {
293 "dry-run"
294 } else {
295 &ctx.job_id
296 },
297 );
298 if ctx.project {
299 let lines = if flags.dry_run {
300 project::dry_run(&plan)
301 } else {
302 project::header(&plan, true)
303 };
304 for line in lines {
305 emit(&line);
306 }
307 } else {
308 for lane in &lanes {
309 print_header(&ctx, lane, !flags.dry_run);
310 }
311 }
312 if flags.dry_run {
313 for lane in &lanes {
314 for line in lane::dead_run_notes(&ctx, &lane.inst) {
315 emit(&line);
316 }
317 }
318 let blocked: Vec<&str> = lanes
319 .iter()
320 .filter(|l| !l.blocked.is_empty())
321 .map(|l| l.ml.slug.as_str())
322 .collect();
323 if !blocked.is_empty() {
324 emit(&format!(
326 "dry-run: preflight failed for {} — the run would end Blocked (stderr says why)",
327 blocked.join(", ")
328 ));
329 emit(&format!("Start: {}", start_command(&flags)));
330 return Ok(2);
331 }
332 emit("dry-run: preflight green; stopping before dispatch");
333 emit(&format!("Start: {}", start_command(&flags)));
334 return Ok(0);
335 }
336
337 sched::orchestrate(ctx, lanes, plan)
338}
339
340fn start_command(flags: &RunFlags) -> String {
343 let mut words = vec!["vitrify".to_string(), "run".to_string()];
344 if let Some(cap) = flags.cap {
345 words.extend(["--cap".to_string(), cap.to_string()]);
346 }
347 if let Some(jobs) = flags.gate_jobs {
348 words.extend(["--gate-jobs".to_string(), jobs.to_string()]);
349 }
350 if flags.wait {
351 words.push("--wait".to_string());
352 }
353 if flags.recheck {
354 words.push("--recheck".to_string());
355 }
356 if let Some(sdd) = &flags.sdd {
357 words.extend(["--sdd".to_string(), shell_word(sdd)]);
358 }
359 if flags.upstream {
360 words.push("--upstream".to_string());
361 }
362 if let Some(branch) = &flags.mainline {
363 words.extend(["--mainline".to_string(), shell_word(branch)]);
364 }
365 words.join(" ")
366}
367
368pub(crate) fn shell_word(s: &str) -> String {
371 let plain = !s.is_empty()
372 && s.chars()
373 .all(|c| c.is_ascii_alphanumeric() || "-_./:@+=,%".contains(c));
374 if plain {
375 s.to_string()
376 } else {
377 format!("'{}'", s.replace('\'', "'\\''"))
378 }
379}
380
381fn with_fix(cause: &str, fix: &str) -> String {
384 let cause = cause.strip_prefix("error: ").unwrap_or(cause);
385 match cause.split_once('\n') {
386 Some((first, rest)) => format!("{first} → {fix}\n{rest}"),
387 None => format!("{cause} → {fix}"),
388 }
389}
390
391fn sdd_failure(cause: &str) -> String {
395 let cause = cause.strip_prefix("error: ").unwrap_or(cause);
396 let first = cause.lines().next().unwrap_or_default();
397 if first.contains(" → ") {
398 return cause.to_string();
399 }
400 let fix = if cause.contains("no SDD found") {
401 "vitrify brief authoring"
402 } else if cause.contains("multiple SDDs") || cause.contains("several SDDs") {
403 "pass one of these --sdd values"
404 } else {
405 "vitrify locate"
406 };
407 match first.strip_suffix(':') {
408 Some(lead) => format!("{lead} → {fix}:{}", &cause[first.len()..]),
409 None => with_fix(cause, fix),
410 }
411}
412
413fn select_harness(home: &Path, cfg: &Config) -> (Option<String>, Option<Vec<String>>) {
414 let order: Vec<&str> = if cfg.harness.preferred.is_empty() {
415 vec!["claude", "codex", "opencode"]
416 } else {
417 vec![cfg.harness.preferred.as_str()]
418 };
419 for name in order {
420 if let Some(argv) = cmd::probe::recorded_headless(home, name) {
421 return (Some(name.to_string()), Some(argv));
422 }
423 }
424 (None, None)
425}
426
427fn preflight(
435 ctx: &mut Ctx,
436 failures: &mut Vec<String>,
437 dry_run: bool,
438) -> Result<Result<Vec<LaneSeed>, u8>, CoreError> {
439 let chosen = match choose_lanes(ctx, failures)? {
440 Ok(chosen) => chosen,
441 Err(code) => return Ok(Err(code)),
442 };
443 let mut lanes: Vec<LaneSeed> = chosen
444 .into_iter()
445 .map(|(sdd_rel, inst)| {
446 let slug = layout::sdd_slug(&inst);
447 LaneSeed {
448 ml: ctx.mainline_for(sdd_rel, slug),
449 inst,
450 cap: usize::MAX,
451 rotten: Vec::new(),
452 blocked: Vec::new(),
453 checked: Vec::new(),
454 suite_ran: false,
455 }
456 })
457 .collect();
458
459 let usable_root = project_preflight(ctx, &lanes, failures);
460 if ctx.project {
461 if !failures.is_empty() {
462 return Ok(Err(2));
463 }
464 for lane in &mut lanes {
465 let mut own: Vec<String> = Vec::new();
466 if !lane_static(ctx, lane, &mut own, dry_run)? {
467 return Ok(Err(2));
468 }
469 if dry_run && own.is_empty() && usable_root {
475 if !lane_dynamic(ctx, lane, &mut own, dry_run, false)? {
476 return Ok(Err(2));
477 }
478 if ctx.cfg.run.lane_limit().is_some() {
479 lane.ml.remove_checkouts();
480 }
481 }
482 for f in &own {
483 diag(&project::event_line(
484 &lane.ml.slug,
485 &format!("preflight failed: {f}"),
486 ));
487 }
488 lane.blocked = own;
489 }
490 } else {
491 for lane in &lanes {
492 if !lane_static(ctx, lane, failures, dry_run)? {
493 return Ok(Err(2));
494 }
495 }
496 if usable_root {
499 for lane in &mut lanes {
500 if !lane_dynamic(ctx, lane, failures, dry_run, true)? {
501 return Ok(Err(2));
502 }
503 }
504 }
505 }
506
507 for lane in &mut lanes {
508 if lane.inst.shape == Shape::Single {
510 lane.cap = 1;
511 if ctx.cap > 1 && !ctx.project {
512 diag(
513 "note: single-file SDD — worker cap forced to 1 (every status edit shares one file)",
514 );
515 }
516 }
517 }
518 let room = lanes.iter().fold(0usize, |n, l| n.saturating_add(l.cap));
520 ctx.cap = ctx.cap.min(room).max(1);
521
522 if failures.is_empty() {
523 Ok(Ok(lanes))
524 } else {
525 Ok(Err(2))
526 }
527}
528
529fn choose_lanes(
535 ctx: &mut Ctx,
536 failures: &mut Vec<String>,
537) -> Result<Result<Vec<(PathBuf, Instance)>, u8>, CoreError> {
538 let root = ctx.primary.dir.clone();
539 if ctx.upstream && ctx.sdd_arg.is_none() {
540 failures.push(with_fix(
541 "--upstream adds the SDDs an SDD depends on, and names none",
542 "pass --sdd <root> with it",
543 ));
544 return Ok(Err(2));
545 }
546 let project_wide = ctx.sdd_arg.is_none() && cmd::discover(&root).len() > 1;
547 if !project_wide && !ctx.upstream {
548 return Ok(match resolve_lane(ctx, failures)? {
549 Some(lane) => Ok(vec![lane]),
550 None => Err(2),
551 });
552 }
553 let named = if ctx.upstream {
554 match resolve_lane(ctx, failures)? {
555 Some(lane) => Some(lane),
556 None => return Ok(Err(2)),
557 }
558 } else {
559 None
560 };
561
562 let (all, refused) = cmd::loaded(&root, named.as_ref().map(|(_, i)| i));
564 for (_, e) in &refused {
565 failures.push(sdd_failure(&e.to_string()));
566 }
567 if !failures.is_empty() {
568 return Ok(Err(2));
569 }
570 let graph = match project::preflight(&all) {
571 Ok(graph) => graph,
572 Err(refused) => {
573 failures.extend(refused.failures);
574 return Ok(Err(refused.code));
575 }
576 };
577 let active = |i: &Instance| i.meta.get_str_or("status", "Draft") == "Active";
578 let mut chosen: Vec<&Instance> = match &named {
579 Some((_, inst)) => {
580 let slugs = project::select_lanes(&graph, vitrify_core::graph::slug_of(inst), true)
581 .unwrap_or_default();
582 all.iter()
583 .filter(|i| {
584 i.root == inst.root
585 || (active(i) && slugs.iter().any(|s| s == vitrify_core::graph::slug_of(i)))
586 })
587 .collect()
588 }
589 None => all.iter().filter(|i| active(i)).collect(),
590 };
591 if chosen.is_empty() {
592 failures.push(with_fix(
593 "no SDD of the repository is Active",
594 "finish authoring one and set it Active: vitrify brief authoring",
595 ));
596 return Ok(Err(2));
597 }
598 chosen.sort_by(|a, b| vitrify_core::graph::slug_of(a).cmp(vitrify_core::graph::slug_of(b)));
599 ctx.project = project_wide || chosen.len() > 1;
600 Ok(Ok(chosen
601 .into_iter()
602 .map(|i| {
603 let rel = cmd::sdd_rel(&root, &i.root).unwrap_or_else(|| i.root.clone());
604 (rel, i.clone())
605 })
606 .collect()))
607}
608
609fn resolve_lane(
613 ctx: &Ctx,
614 failures: &mut Vec<String>,
615) -> Result<Option<(PathBuf, Instance)>, CoreError> {
616 let root = ctx.primary.dir.clone();
617 let located = match ctx.sdd_arg.as_deref() {
621 Some(arg) => {
622 let here = cmd::repo_root();
623 cmd::resolve_sdd(&here, Some(arg), &cmd::cwd()).map(|h| {
624 cmd::sdd_rel(&here, &h.root)
625 .or_else(|| cmd::sdd_rel(&root, &h.root))
626 .ok_or(h.root)
627 })
628 }
629 None => cmd::resolve_sdd(&root, None, &cmd::cwd())
630 .map(|h| cmd::sdd_rel(&root, &h.root).ok_or(h.root)),
631 };
632 let sdd_rel = match located {
635 Ok(Ok(rel)) => rel,
636 Ok(Err(outside)) => {
637 failures.push(with_fix(
638 &format!(
639 "SDD {} is outside the repository {}",
640 outside.display(),
641 root.display()
642 ),
643 "pass an --sdd inside this repository",
644 ));
645 return Ok(None);
646 }
647 Err(e) => {
648 failures.push(sdd_failure(&e.to_string()));
649 return Ok(None);
650 }
651 };
652 match cmd::resolve_sdd_in(&root, &sdd_rel).and_then(Instance::load) {
654 Ok(inst) => Ok(Some((sdd_rel, inst))),
655 Err(e) => {
656 failures.push(sdd_failure(&e.to_string()));
657 Ok(None)
658 }
659 }
660}
661
662fn project_preflight(ctx: &Ctx, lanes: &[LaneSeed], failures: &mut Vec<String>) -> bool {
666 if ctx.push {
671 let _ = ctx.primary.fetch_origin(&ctx.branch);
672 let local = ctx.primary.rev_parse(&format!("refs/heads/{}", ctx.branch));
673 let remote = ctx
674 .primary
675 .rev_parse(&format!("refs/remotes/origin/{}", ctx.branch));
676 if let (Ok(local), Ok(remote)) = (local, remote)
677 && local != remote
678 && !ctx.primary.is_ancestor(&local, &remote).unwrap_or(false)
679 {
680 failures.push(with_fix(
681 &format!(
682 "the local {b} holds commits origin/{b} does not — the run builds origin's head, so they would be left out",
683 b = ctx.branch
684 ),
685 &format!("publish them first: git push origin {}", shell_word(&ctx.branch)),
686 ));
687 }
688 }
689 let others = cmd::discover(&ctx.primary.dir);
692 for lane in lanes {
693 for other in &others {
694 if other.root != lane.inst.root
695 && layout::slug_of(&other.meta, &other.root, other.shape) == lane.ml.slug
696 {
697 failures.push(with_fix(
698 &format!(
699 "SDD slug `{}` is also used by {} — branch and worktree names would collide",
700 lane.ml.slug,
701 other.root.display()
702 ),
703 "rename one of the `sdd:` slugs",
704 ));
705 }
706 }
707 }
708
709 if ctx.argv.is_empty() {
711 failures.push(with_fix(
712 "~/.vitrify/config.toml records no working harness",
713 "vitrify probe",
714 ));
715 }
716 if let Some(e) = &ctx.profile_error {
717 failures.push(with_fix(
718 e,
719 "correct the line the error names, then vitrify probe",
720 ));
721 }
722
723 match ctx.layout.ensure_worktree_root(&ctx.primary) {
725 Ok(()) => true,
726 Err(e) => {
727 failures.push(with_fix(
728 &e.to_string(),
729 "point run.worktree_dir at a directory no ignore file of the repository covers",
730 ));
731 false
732 }
733 }
734}
735
736fn lane_static(
743 ctx: &Ctx,
744 lane: &LaneSeed,
745 failures: &mut Vec<String>,
746 dry_run: bool,
747) -> Result<bool, CoreError> {
748 let root = &ctx.primary.dir;
749 let inst = &lane.inst;
750 let sdd_word = shell_word(&cmd::sdd_arg(&lane.ml.sdd_rel));
751 if inst.meta.get_str_or("status", "Draft") != "Active" {
752 failures.push(with_fix(
753 &format!(
754 "SDD status is {}, not Active",
755 inst.meta.get_str_or("status", "Draft")
756 ),
757 "finish authoring and set it Active: vitrify brief authoring",
758 ));
759 }
760 let porcelain = ctx.primary.status_porcelain().map_err(CoreError::from)?;
762 let spec_rel = cmd::sdd_arg(&lane.ml.sdd_rel);
763 let under_spec =
764 |p: &str| spec_rel == "." || p == spec_rel || p.starts_with(&format!("{spec_rel}/"));
765 let dirty_spec: Vec<&str> = porcelain
766 .lines()
767 .filter(|l| l.split_whitespace().nth(1).is_some_and(under_spec))
768 .collect();
769 if !dirty_spec.is_empty() {
770 if crate::cmd::claim::behind_note(&ctx.primary, &ctx.branch).is_some() {
771 failures.push(with_fix(
773 &format!(
774 "the primary checkout is behind {} — its copy of the SDD is not the one at the mainline head",
775 ctx.branch
776 ),
777 "bring it up to date as the note above says",
778 ));
779 } else {
780 failures.push(with_fix(
781 &format!(
782 "SDD not committed at the mainline head (uncommitted spec changes): {}",
783 dirty_spec.join("; ")
784 ),
785 &format!("commit or stash the changes under {sdd_word}"),
786 ));
787 }
788 }
789
790 let lint_findings = cmd::lint::pre_run_findings(inst, root, ctx.cfg.lint.readset_budget_bytes)?;
793 for x in &lint_findings {
794 failures.push(with_fix(
795 &format!("lint [{}] {}: {}", x.check, x.subject, x.cause),
796 &x.remediation,
797 ));
798 }
799
800 let (findings, _) = audit::run(
802 inst,
803 root,
804 &cmd::audit_options(
805 audit::Options {
806 skip_rotten: true,
807 ..Default::default()
808 },
809 root,
810 inst,
811 ),
812 &ShRunner,
813 UtcTime::now(),
814 )?;
815 if signals::interrupted() {
816 return Ok(false);
817 }
818 let audit_clean = findings.is_empty();
819 if !audit_clean {
820 if findings.iter().all(|f| f.check == 7) {
821 if dry_run {
822 diag(&format!(
824 "preflight: {} lapsed lease(s) — a run releases them before it starts",
825 findings.len()
826 ));
827 } else {
828 lane.ml.heal(true, false)?;
829 diag(&format!(
830 "preflight: {} lapsed lease(s) fixed and published",
831 findings.len()
832 ));
833 }
834 } else {
835 for f in &findings {
836 failures.push(with_fix(
837 &format!("audit [check {}] {}: {}", f.check, f.subject, f.cause),
838 &f.remediation,
839 ));
840 }
841 }
842 }
843 Ok(true)
844}
845
846fn lane_dynamic(
855 ctx: &Ctx,
856 lane: &mut LaneSeed,
857 failures: &mut Vec<String>,
858 dry_run: bool,
859 recheck: bool,
860) -> Result<bool, CoreError> {
861 let note = || {
862 diag(
863 "note: another vitrify process is integrating this SDD — waiting for its integration checkout",
864 )
865 };
866 let Some((checkout, head)) = dynamic_checks(&lane.ml, failures, ¬e)? else {
867 return Ok(false);
868 };
869 if !failures.is_empty() || !recheck {
870 return Ok(true);
871 }
872 lane_recheck(ctx, lane, &checkout, &head, dry_run)
873}
874
875pub(crate) fn dynamic_checks(
880 ml: &Mainline,
881 failures: &mut Vec<String>,
882 waiting: &dyn Fn(),
883) -> Result<Option<(PathBuf, String)>, CoreError> {
884 let Some(_held) = ml.lock_checkout(waiting)? else {
885 return Ok(None);
886 };
887 let head = ml.head()?;
888 let checkout = ml.recreate_checkout(&head)?;
889 let inst = ml.sdd_in(&checkout)?;
890 let cmds = integrate::sdd_commands(&model::read_text(&inst.file)?);
891 let steps: [(&str, &Option<String>); 3] = [
892 ("bootstrap", &cmds.bootstrap),
893 ("build", &cmds.build),
894 ("lint", &cmds.lint),
895 ];
896 for (name, cmd_opt) in steps {
897 let Some(c) = cmd_opt else {
898 failures.push(with_fix(
899 &format!("§5 Commands block missing the {name} command"),
900 &format!("add the {name} command to the SDD's §5 Commands"),
901 ));
902 continue;
903 };
904 let (ok, output) = integrate::run_gate_command(c, &checkout);
905 if signals::interrupted() {
906 return Ok(None);
907 }
908 if !ok {
909 let quoted = tail(&output, 5);
910 let cause = format!("§5 {name} command failed: {c}");
911 let fix = "run it from the repository root and fix what it reports";
912 failures.push(if quoted.is_empty() {
913 with_fix(&cause, fix)
914 } else {
915 format!("{}\n{quoted}", with_fix(&cause, fix))
916 });
917 }
918 }
919 Ok(Some((checkout, head)))
920}
921
922fn lane_recheck(
930 ctx: &Ctx,
931 lane: &mut LaneSeed,
932 checkout: &Path,
933 head: &str,
934 dry_run: bool,
935) -> Result<bool, CoreError> {
936 let git = ctx.primary.at(checkout);
937 let slug = vitrify_core::graph::slug_of(&lane.inst).to_string();
938 let mode = if ctx.recheck {
939 Mode::Everything
940 } else {
941 Mode::Changes
942 };
943 let units: Vec<String> =
944 match Snapshot::load(&git, checkout, head).and_then(|snap| snap.dirty(&git, mode)) {
945 Ok(Cascade::Resolved(set)) => set.of_sdd(&slug).map(|d| d.node.unit.clone()).collect(),
946 _ => lane
949 .inst
950 .units
951 .iter()
952 .filter(|u| u.meta.get_str_or("status", "Draft") == "Verified")
953 .map(|u| u.unit.clone())
954 .collect(),
955 };
956 if units.is_empty() {
957 return Ok(true);
958 }
959 let report = recheck::run(
960 &git,
961 head,
962 &lane.ml.sdd_rel,
963 &units,
964 &integrate::PoolRunner(ctx.cfg.run.rows_at_once()),
965 )?;
966 if report.interrupted || signals::interrupted() {
967 return Ok(false);
968 }
969 if let Some(broken) = &report.broken {
970 diag(&format!(
971 "note: the re-check could not run: `{}` failed at {}",
972 broken.command,
973 &head[..head.len().min(7)]
974 ));
975 return Ok(true);
976 }
977 lane.rotten
979 .extend(integrate::rotten_of(&lane.inst, &report)?);
980 lane.checked = report.units.iter().map(|u| u.unit.clone()).collect();
981 lane.suite_ran = report.suite.is_some();
982 let edits = report.edits();
983 if !edits.verified.is_empty() {
984 diag(&format!(
985 "preflight: re-checked {} at {}{}",
986 edits.verified.join(", "),
987 edits.commit,
988 if dry_run {
989 " (a dry run records nothing)"
990 } else {
991 ""
992 }
993 ));
994 }
995 if !dry_run {
996 integrate::record_recheck(&lane.ml, &edits);
997 }
998 Ok(true)
999}
1000
1001pub(crate) fn tail(text: &str, n: usize) -> String {
1004 let lines: Vec<&str> = text.lines().filter(|l| !l.trim().is_empty()).collect();
1005 let start = lines.len().saturating_sub(n);
1006 lines[start..].join("\n")
1007}
1008
1009fn print_header(ctx: &Ctx, lane: &LaneSeed, watch: bool) {
1013 let inst = &lane.inst;
1014 let slug = inst.meta.get_str_or("sdd", "?");
1015 let version = inst.meta.get_str_or("version", "?");
1016 emit(&format!(
1017 "SDD build job — {slug} @ {version} [{}]",
1018 ctx.job_id
1019 ));
1020 let has_test = model::read_text(&inst.file)
1021 .map(|text| integrate::sdd_commands(&text).test.is_some())
1022 .unwrap_or(false);
1023 emit(&format!(
1024 "Done-condition: every non-Retired unit Verified @ {version}; audit clean; replay clean{}",
1025 if has_test { "; §5 Test passing" } else { "" }
1026 ));
1027 emit(&format!(
1028 "Mainline: {} Remote: {} Shape: {}",
1029 ctx.branch,
1030 if ctx.push { "origin" } else { "none" },
1031 inst.shape.as_str()
1032 ));
1033 emit(&format!("Plan: {}", plan(inst)));
1034 emit(&format!(
1035 "Workers: cap={} Holder IDs: {}-w<i> Harness: {}",
1036 ctx.cap,
1037 ctx.job_id,
1038 if ctx.harness.is_empty() {
1039 "-"
1040 } else {
1041 &ctx.harness
1042 }
1043 ));
1044 if !ctx.roles.is_empty() && !ctx.harness.is_empty() {
1045 emit(&format!("Roles: {}", ctx.roles.join(" ")));
1046 }
1047 emit(&format!(
1048 "Worktrees: {} Branches: sdd/{}/<unit>/c<seq>",
1049 ctx.layout.wt_root.display(),
1050 lane.ml.slug
1051 ));
1052 emit(&format!(
1053 "Parameters: worker cap {} · gate jobs {}{} · lease {}m · renew at {} remaining · escalate after {} failed attempts of a unit, set it aside after {}",
1054 ctx.cap,
1055 ctx.gate_pool.size(),
1056 if ctx.cfg.run.rows_follow_cores() {
1057 " (one per core)"
1058 } else {
1059 ""
1060 },
1061 ctx.cfg.run.lease_minutes,
1062 ctx.cfg.run.renew_fraction,
1063 ctx.cfg.run.abort_failed_waves.max(1),
1064 ctx.cfg.run.abort_failed_waves.max(1) * 2
1065 ));
1066 if watch {
1067 emit(&format!(
1068 "Watch: vitrify run status --job {} [--follow] · once it ends, the same command prints the report · procedure: vitrify brief run",
1069 ctx.job_id
1070 ));
1071 }
1072}
1073
1074fn plan(inst: &Instance) -> String {
1078 let mut parts: Vec<String> = Vec::new();
1079 let mut units: Vec<&model::Unit> = inst.units.iter().collect();
1080 units.sort_by(|a, b| a.unit.cmp(&b.unit));
1081 let mut seen_groups: Vec<String> = Vec::new();
1082 for u in &units {
1083 let status = u.meta.get_str_or("status", "Draft");
1084 let group = u.meta.get_str_or("parallel_group", "").trim().to_string();
1085 if model::is_empty_marker(&group) {
1086 parts.push(format!("{} ({status})", u.unit));
1087 } else if !seen_groups.contains(&group) {
1088 seen_groups.push(group.clone());
1089 let members: Vec<String> = units
1090 .iter()
1091 .filter(|x| x.meta.get_str_or("parallel_group", "").trim() == group)
1092 .map(|x| x.unit.clone())
1093 .collect();
1094 parts.push(format!("[P:{group}] {}", members.join(", ")));
1095 }
1096 }
1097 parts.join(" → ")
1098}
1099
1100pub(crate) struct WorkerRec {
1104 pub lane: String,
1107 pub holder: String,
1108 pub pid: u32,
1109 pub unit: String,
1110 pub claim_seq: i64,
1111 pub branch: String,
1112 pub worktree: String,
1113 pub started_at: String,
1114 pub ended_at: Option<String>,
1115 pub outcome: String,
1117 pub retry: bool,
1120 pub detail: Option<String>,
1123}
1124
1125#[derive(Default)]
1127pub(crate) struct RunState {
1128 pub workers: Vec<WorkerRec>,
1129 pub reports: Vec<String>,
1130 pub escalations: Vec<(String, String)>, pub report: Option<Vec<String>>,
1134}
1135
1136fn write_record(dir: &Path, name: &str, body: &str) -> Result<(), CoreError> {
1139 std::fs::create_dir_all(dir).map_err(|source| CoreError::Io {
1140 path: dir.to_path_buf(),
1141 source,
1142 })?;
1143 let path = dir.join(name);
1144 let tmp = dir.join(format!("{name}.tmp"));
1145 std::fs::write(&tmp, body).map_err(|source| CoreError::Io {
1146 path: tmp.clone(),
1147 source,
1148 })?;
1149 std::fs::rename(&tmp, &path).map_err(|source| CoreError::Io { path, source })
1150}
1151
1152pub(crate) fn write_run_json(
1157 ctx: &Ctx,
1158 sdd: &str,
1159 state: &RunState,
1160 started_at: &str,
1161 terminated: Option<(&str, &str)>,
1162) -> Result<(), CoreError> {
1163 let workers: Vec<J> = state
1164 .workers
1165 .iter()
1166 .map(|w| {
1167 J::Obj(vec![
1168 ("holder".into(), J::s(w.holder.clone())),
1169 ("pid".into(), J::Int(w.pid as i64)),
1170 ("unit".into(), J::s(w.unit.clone())),
1171 ("claim_seq".into(), J::Int(w.claim_seq)),
1172 ("branch".into(), J::s(w.branch.clone())),
1173 ("worktree".into(), J::s(w.worktree.clone())),
1174 ("started_at".into(), J::s(w.started_at.clone())),
1175 ("ended_at".into(), J::opt_str(w.ended_at.clone())),
1176 ("outcome".into(), J::s(w.outcome.clone())),
1177 ("retry".into(), J::Bool(w.retry)),
1178 ("detail".into(), J::opt_str(w.detail.clone())),
1179 ("lane".into(), J::s(w.lane.clone())),
1180 ])
1181 })
1182 .collect();
1183 let escalations: Vec<J> = state
1184 .escalations
1185 .iter()
1186 .map(|(p, v)| {
1187 J::Obj(vec![
1188 ("evidence_path".into(), J::s(p.clone())),
1189 ("verdict".into(), J::s(v.clone())),
1190 ])
1191 })
1192 .collect();
1193 let mut pairs = vec![
1194 ("job_id".into(), J::s(ctx.job_id.clone())),
1195 ("pid".into(), J::Int(std::process::id() as i64)),
1196 ("sdd".into(), J::s(sdd)),
1197 ("harness".into(), J::s(ctx.harness.clone())),
1198 ("started_at".into(), J::s(started_at)),
1199 (
1200 "done_condition".into(),
1201 J::s(
1202 "every non-Retired unit Verified @ current SDD version; audit clean; replay clean; §5 Test passing (when the SDD has one)",
1203 ),
1204 ),
1205 (
1206 "params".into(),
1207 J::Obj(vec![
1208 ("cap".into(), J::Int(ctx.cap as i64)),
1209 ("gate_jobs".into(), J::Int(ctx.gate_pool.size() as i64)),
1210 ("lease_minutes".into(), J::Int(ctx.cfg.run.lease_minutes)),
1211 (
1212 "worker_timeout_minutes".into(),
1213 J::Int(ctx.cfg.run.worker_timeout_minutes),
1214 ),
1215 (
1216 "abort_failed_waves".into(),
1217 J::Int(ctx.cfg.run.abort_failed_waves),
1218 ),
1219 ]),
1220 ),
1221 (
1222 "worktrees".into(),
1223 J::s(ctx.layout.wt_root.display().to_string()),
1224 ),
1225 ("workers".into(), J::Arr(workers)),
1226 (
1227 "reports".into(),
1228 J::Arr(state.reports.iter().map(|r| J::s(r.clone())).collect()),
1229 ),
1230 ("escalations".into(), J::Arr(escalations)),
1231 ];
1232 if let Some((end_state, detail)) = terminated {
1233 pairs.push((
1234 "terminated".into(),
1235 J::Obj(vec![
1236 ("state".into(), J::s(end_state)),
1237 ("at".into(), J::s(UtcTime::now().format())),
1238 ("detail".into(), J::s(detail)),
1239 ]),
1240 ));
1241 }
1242 pairs.push((
1243 "report".into(),
1244 state.report.as_ref().map_or(J::Null, |lines| {
1245 J::Arr(lines.iter().map(|l| J::s(l.clone())).collect())
1246 }),
1247 ));
1248 let body = J::Obj(pairs).dumps_indent2();
1249 ctx.layout.ensure_scratch()?;
1250 for dir in [&ctx.layout.scratch, &ctx.logs_dir] {
1251 write_record(dir, "run.json", &body)?;
1252 }
1253 Ok(())
1254}