Skip to main content

vitrify_cli/run/
mod.rs

1//! `vitrify run` — the deterministic orchestrator: preflight, continuous
2//! dispatch, batched serial integration, termination reports. Control flow
3//! is Rust; inference happens only at the three enumerated points: workers,
4//! escalation, and plan-time authoring (outside `run`).
5//! Resume = re-derivation from repo state, never memory.
6//!
7//! A run builds its SDDs as lanes, one per SDD ([`lane`]), under one
8//! scheduler ([`sched`]). A plain `vitrify run` in a repository of several
9//! SDDs is a **project run**: every Active SDD is a lane (`--sdd` with
10//! `--upstream`: that SDD and those it depends on). One SDD — the only one,
11//! or the one `--sdd` names — is built exactly as it always was. What the lanes share is the run's: the worker
12//! cap, the gate pool, the event log, the run record. Preflight has three
13//! parts: the project's (before anything runs), each lane's static checks
14//! (at the start), and each lane's dynamic checks (its §5 commands in its
15//! own checkout, before its first build, then a re-check of the units a
16//! change reached since their last recorded check — and only those).
17
18pub 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    /// Override `run.gate_jobs`.
59    pub gate_jobs: Option<i64>,
60    /// Stay alive when only blocked units remain, and resume when the spec
61    /// changes.
62    pub wait: bool,
63    /// Trust no recorded check: every Verified unit's rows and the §5 Test
64    /// command run again. Nothing is rebuilt for it, and built attempts are
65    /// still adopted — they pass the full gate either way.
66    pub recheck: bool,
67    /// With `sdd`: build the SDDs it depends on too, each a lane.
68    pub upstream: bool,
69}
70
71/// What every lane of a run shares: the repository, the configuration, the
72/// harness, the caps, the job.
73pub(crate) struct Ctx {
74    /// The primary checkout.
75    pub primary: Git,
76    pub layout: Layout,
77    /// The mainline branch.
78    pub branch: String,
79    /// Publish by `git push` (origin arbitrates) rather than a local CAS.
80    pub push: bool,
81    pub cfg: Config,
82    /// Model sessions at once, across every lane.
83    pub cap: usize,
84    /// Commands at once — §5 commands and Verification rows — across every
85    /// gate, head check and preflight of the run.
86    pub gate_pool: &'static Pool,
87    pub home: PathBuf,
88    pub harness: String,
89    /// The headless spelling the probe recorded for the selected harness.
90    pub argv: Vec<String>,
91    /// `argv` + the worker role's model/effort flags from config.toml.
92    pub worker_argv: Vec<String>,
93    /// `argv` + the retry role's flags (the worker's, unless config.toml
94    /// names a retry profile).
95    pub retry_argv: Vec<String>,
96    /// `argv` + the escalation role's model/effort flags.
97    pub escalation_argv: Vec<String>,
98    /// Per-role summaries for the job header.
99    pub roles: Vec<String>,
100    /// The role profiles in config.toml failed to read or parse (a
101    /// preflight failure).
102    pub profile_error: Option<String>,
103    pub sdd_arg: Option<String>,
104    pub job_id: String,
105    /// `.vitrify/logs/<job>/`: the job's own records.
106    pub logs_dir: PathBuf,
107    pub wait: bool,
108    /// `--recheck`: no recorded check is trusted; preflight re-checks every
109    /// Verified unit and the §5 Test command.
110    pub recheck: bool,
111    /// `--upstream`.
112    pub upstream: bool,
113    /// A project run: lanes are named on every line, the header, report and
114    /// preflight are the project's, and a lane whose preflight fails is
115    /// blocked instead of refusing the run.
116    pub project: bool,
117}
118
119impl Ctx {
120    /// The mainline handle of a lane: the SDD at `sdd_rel`, named `slug`,
121    /// in this run's repository.
122    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
134/// One lane as preflight leaves it, for the scheduler to start.
135pub(crate) struct LaneSeed {
136    /// The SDD, pinned: its path, its slug, the repository it is built in.
137    pub ml: Mainline,
138    /// The SDD as the primary checkout held it at preflight.
139    pub inst: Instance,
140    /// Workers at once in this lane: 1 for a single-file SDD, whose every
141    /// status edit shares one file.
142    pub cap: usize,
143    /// Rows the preflight re-check found failing: their units are rotten
144    /// from the start.
145    pub rotten: Vec<RottenRow>,
146    /// Why its preflight failed, in a project run: the lane is blocked, and
147    /// so is every unit that depends on its units.
148    pub blocked: Vec<String>,
149    /// Units the preflight re-check checked, and whether it ran the §5 Test
150    /// command: under `--recheck` they need no second check.
151    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    // the home holds the probe record, the role profiles and the worktrees:
176    // `vitrify init` sets it up, and nothing here creates it
177    home::require_set_up(&home)?;
178    let layout = Layout::resolve(&root, Some(&home), &cfg.run.worktree_dir)?;
179
180    // harness: preferred, else the first the probe recorded of claude,
181    // codex, opencode
182    let (harness, argv) = select_harness(&home, &cfg);
183    let harness = harness.unwrap_or_default();
184    let argv = argv.unwrap_or_default();
185    // per-role model/effort: the [harness.<name>] tables of config.toml,
186    // a repository's own config.toml overriding them key by key
187    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    // one bound on the commands the run starts, whichever lane starts them
220    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    // From here an interrupt is ours to handle: the commands preflight runs
248    // and the workers the loop starts are stopped by vitrify, not left
249    // running behind a dead parent.
250    signals::install();
251    crate::cmd::claim::quiet_resync(true);
252
253    // A primary checkout that an earlier commit could not move is behind
254    // mainline: it catches up before preflight reads it (a dry run only
255    // says so).
256    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(&note);
264    }
265
266    // ---------------- preflight: refuse to start on any failure
267    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    // ---------------- job header BEFORE dispatch
287    // A dry run records no job: its plan names none, so the same repository
288    // state and configuration print the same plan.
289    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            // the run would end Blocked: say so, and exit as it would
325            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
340/// The command that starts the run a dry run checked: the flags given,
341/// without `--dry-run`, in the order the usage line lists them.
342fn 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
368/// `s` as one shell word: as it is when nothing in it needs quoting, else
369/// single-quoted.
370pub(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
381/// A preflight failure with its fix: ` → <fix>` closes the first line (a
382/// cause can carry what it lists on the lines after).
383fn 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
391/// An SDD that did not resolve or load, with its fix. A refusal that names
392/// its next step already keeps its own; one that lists `--sdd` values
393/// after a colon keeps the colon after the fix.
394fn 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
427// ---------------------------------------------------------------- preflight
428
429/// Preflight: which SDDs the run builds, the project's checks, then each
430/// lane's static checks, then each lane's dynamic checks. Every failure
431/// found is collected. With one lane any failure refuses the run; in a
432/// project run a lane whose own checks fail is blocked, and the rest go on.
433/// `Err(code)` = refused (or interrupted).
434fn 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            // A lane's dynamic preflight runs at its first build or
470            // re-check, when the scheduler admits it, and its re-checks in
471            // the loop, in dependency order. A dry run has no loop: it runs
472            // them here, one lane at a time, and keeps no checkout beyond
473            // `run.lane_cap`.
474            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        // a lane's commands run in its own checkout, made under the
497        // worktree root: without a usable root there is nowhere to run them
498        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        // single-file shape forces cap 1
509        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    // the run never starts more workers than its lanes can take
519    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
529/// Which SDDs the run builds, each pinned as its path under the repository
530/// root and loaded from the primary checkout: `--sdd`'s, or the only one;
531/// in a repository of several, every Active SDD — a project run, refused
532/// (exit 4 or 2) when the repository as a whole does not hold together;
533/// `--sdd` with `--upstream`: that SDD and the SDDs it depends on.
534fn 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    // the repository as a whole
563    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
609/// The SDD the run builds — `--sdd`, else the only one — pinned as its path
610/// under the repository root and loaded from the primary checkout. `None`
611/// (with the failure recorded) when there is no such SDD.
612fn resolve_lane(
613    ctx: &Ctx,
614    failures: &mut Vec<String>,
615) -> Result<Option<(PathBuf, Instance)>, CoreError> {
616    let root = ctx.primary.dir.clone();
617    // SDD located. `--sdd` is a path from where the verb runs, which may be
618    // a linked worktree: what it names there is found by its path under that
619    // checkout's root. Without it, the primary checkout is searched.
620    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    // Pin it: from here on the SDD is this path under the repository root,
633    // in whichever checkout is being read — never searched for again.
634    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    // preflight judges the primary checkout's copy
653    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
662/// The project's preflight, before anything runs: the local mainline not
663/// ahead of origin, each lane's slug its SDD's alone, a harness recorded,
664/// the worktree root usable. Returns whether the worktree root is usable.
665fn project_preflight(ctx: &Ctx, lanes: &[LaneSeed], failures: &mut Vec<String>) -> bool {
666    // origin arbitrates: the run builds origin's head, not the local
667    // branch's. Commits the local branch holds and origin does not would be
668    // read here (the SDD, its version, its staleness marks) and then left
669    // out of everything the run builds and reports on.
670    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    // branch, worktree and checkout names carry the slug: it must be its
690    // SDD's alone
691    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    // ≥ 1 working harness probe
710    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    // the worktrees must be somewhere no ignore file of the repository covers
724    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
736/// A lane's static preflight, at the start of the run: its SDD Active and
737/// committed at the mainline head, lint clean, the audit clean (or only
738/// lapsed leases, which are fixed), the journal consistent with front
739/// matter (the audit replays it). The audit runs no Verification row: the
740/// dynamic preflight re-checks what a change reached. `false` =
741/// interrupted.
742fn 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    // committed at the mainline head: spec paths clean in the primary
761    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            // not the user's edits: the checkout holds an earlier commit
772            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    // lint (the resume-tolerant subset; built state is journal-governed once
791    // the SDD is Active)
792    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    // audit clean — or only lapsed leases, fixed and published
801    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                // a dry run publishes nothing
823                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
846/// A lane's dynamic preflight, before its first build: its integration
847/// checkout is made anew at the mainline head — whatever an earlier run
848/// left there is gone — and the §5 Bootstrap, Build and Lint commands run
849/// clean in it, never in the primary checkout. The Test command does not
850/// gate the start: whether tests exist or pass before the build is the
851/// SDD's test posture (schema §10). From the first integration on it gates
852/// as a regression check. Then the lane's re-check ([`lane_recheck`]).
853/// `false` = interrupted.
854fn 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, &note)? 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
875/// A lane's §5 Bootstrap, Build and Lint, in its integration checkout made
876/// anew at the mainline head (under its lock: another run of the SDD may be
877/// gating there — `waiting` is called once if so). Each failure is added to
878/// `failures`. Returns the checkout and the head; `None` = interrupted.
879pub(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
922/// The lane's re-check, in its checkout at `head`: the Verified units a
923/// change reached since their last recorded check (with `--recheck`, every
924/// one) run their rows, then the §5 Test command. Those that pass are
925/// recorded — fresh stamps and `verified` events by `recheck`, and
926/// `suite: "pass"` when the Test command passed — as one mainline commit
927/// (a dry run records nothing). A unit whose rows fail is rotten from the
928/// start. With nothing dirty, nothing runs. `false` = interrupted.
929fn 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            // without a whole repository to cascade along, every Verified
947            // unit is checked
948            _ => 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    // what failed is rotten: something on mainline broke it, or it is flaky
978    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
1001/// The last `n` lines of `text` that say something (blank lines skipped) —
1002/// what a report quotes of a command's output.
1003pub(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
1009/// The job header of one lane. `watch`: the run is starting, so the header
1010/// ends with the command that watches it (a dry run starts nothing to
1011/// watch).
1012fn 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
1074/// The authored plan: units in order, parallel groups named, with current
1075/// state. Dispatch follows `depends_on` alone — every claimable unit, up to
1076/// the cap — so this line is orientation, not a schedule.
1077fn 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
1100// ------------------------------------------------------------- run record
1101
1102/// One dispatched worker, as `run.json` shows it.
1103pub(crate) struct WorkerRec {
1104    /// The slug of the lane it works for: its logs are under
1105    /// `.vitrify/logs/<job>/<lane>/`.
1106    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    /// `running`, then the attempt's outcome.
1116    pub outcome: String,
1117    /// The attempt started from an earlier one's work, so a reader can tell
1118    /// a fresh start from a second try.
1119    pub retry: bool,
1120    /// Why the attempt ended, first line only; `None` while it runs and
1121    /// when it verified, so the record says why without opening the logs.
1122    pub detail: Option<String>,
1123}
1124
1125/// The run's record: what every lane did, in the order it happened.
1126#[derive(Default)]
1127pub(crate) struct RunState {
1128    pub workers: Vec<WorkerRec>,
1129    pub reports: Vec<String>,
1130    pub escalations: Vec<(String, String)>, // (evidence_path, verdict)
1131    /// The final report's lines, from `Complete.` or `Blocked.` on; `None`
1132    /// until it is printed.
1133    pub report: Option<Vec<String>>,
1134}
1135
1136/// Write `body` to `dir/name` whole (tmp + rename), so a reader never sees
1137/// half a record.
1138fn 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
1152/// Write the run record: `.vitrify/run.json` (the latest run in this
1153/// repository) and a copy beside the job's logs. Written when the run
1154/// starts and at every change, so a run that dies leaves its own record —
1155/// including the workers it had running. `sdd` names what the run builds.
1156pub(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}