Skip to main content

vitrify_cli/run/
integrate.rs

1//! The serial integrator: every Built unit that is ready, as one batch, in
2//! the dedicated integration checkout. Fencing check first; then the
3//! write-set check (the branch changed only what the unit may write); a
4//! `--no-ff` merge per unit; the input check (the unit was built from the
5//! spec text mainline holds now); one run of the full integration gate over
6//! the merged tree; one integration commit carrying stamps, journal events,
7//! ledger, and a clean audit; CAS/push publish with lost-race redo; never
8//! leaves mainline failing. A red batch is integrated again one unit at a
9//! time, so one bad unit never holds back the others.
10//!
11//! The gate: the SDD's §5 Bootstrap and Build, the Verification table of
12//! each unit being integrated and of every unit already Verified (each
13//! distinct command once, `run.gate_jobs` at a time), the §5 Lint command,
14//! then the §5 Test command — the whole suite, which a merge must not turn
15//! from passing to failing — and audit checks 1–3.
16
17use std::path::{Path, PathBuf};
18
19use vitrify_core::audit;
20use vitrify_core::journal::Event;
21use vitrify_core::model::{self, Instance, Shape, UtcTime};
22use vitrify_core::writeset::{Violation, WriteSet};
23use vitrify_core::{CoreError, ledger, trace, yamlish};
24
25use super::mainline::{Mainline, append_event};
26use super::progress::GateBoard;
27use crate::cmd::{self, claim};
28use crate::gate::{self, Ran, ShRunner};
29use crate::git::Git;
30use crate::layout;
31use crate::out::diag;
32use crate::signals;
33
34pub struct IntegrateRequest {
35    pub unit: String,
36    pub token_seq: i64,
37    pub builder_holder: String,
38    pub integrator_id: String,
39}
40
41#[derive(Debug, Clone)]
42pub enum Outcome {
43    Verified {
44        merge_commit: String,
45        verify_commit: String,
46    },
47    /// Superseded token or wrong state — rejected outright, tests not run.
48    RejectedFencing { reason: String },
49    /// Token current but the lease merely expired at gate start: not an
50    /// error — the unit returns to the pool.
51    SkippedLeaseExpired,
52    /// The branch changed paths outside the unit's write-set (schema §13.3):
53    /// files the unit does not own (`unmanaged` ones included), other files
54    /// of the SDD, or its own spec text beyond the handoff fields. Rejected
55    /// before merging — nothing merged, nothing published. `detail` holds
56    /// one line per violation.
57    RejectedWriteSet { paths: Vec<String>, detail: String },
58    /// The work does not stamp the unit Built with a recorded trace: there
59    /// is nothing to say what it was built from.
60    RejectedNotBuilt { reason: String },
61    /// The trace the unit was built from no longer matches the spec text at
62    /// the mainline head: an input (`keys`) changed while it was being
63    /// built. Not the work's fault — the unit is rebuilt from current text.
64    RejectedStaleInputs { keys: Vec<String> },
65    /// Gate red: reverted to the recorded base; nothing published.
66    RejectedGate { command: String, output: String },
67    /// Merge conflict. The write-set check already passed, so every
68    /// conflicted path is one this unit may write that mainline also changed
69    /// after the branch forked — treated as an ownership violation: escalate.
70    OwnershipConflict { paths: Vec<String> },
71    /// CAS/push lost after the retry budget.
72    LostRace,
73    /// The run was interrupted before this unit's integration finished;
74    /// nothing was published.
75    Interrupted,
76}
77
78/// The SDD §5 Commands block (`### Commands` in the core file). `vitrify run`
79/// preflight runs bootstrap, build and lint; the integration gate runs all
80/// four — `test` as a regression check (see [`Integrator`]).
81#[derive(Debug, Clone, Default)]
82pub struct SddCommands {
83    pub bootstrap: Option<String>,
84    pub build: Option<String>,
85    pub test: Option<String>,
86    pub lint: Option<String>,
87}
88
89pub fn sdd_commands(core_text: &str) -> SddCommands {
90    let mut out = SddCommands::default();
91    let mut in_section = false;
92    for line in core_text.lines() {
93        if line.starts_with('#') {
94            in_section = line.trim_start_matches('#').trim() == "Commands";
95            continue;
96        }
97        if !in_section {
98            continue;
99        }
100        let Some(rest) = line.trim_start().strip_prefix("- ") else {
101            continue;
102        };
103        let Some((name, value)) = rest.split_once(':') else {
104            continue;
105        };
106        let cmd = value
107            .split('`')
108            .nth(1)
109            .map(str::trim)
110            .filter(|c| !c.is_empty())
111            .map(str::to_string);
112        match name.trim().to_lowercase().as_str() {
113            "bootstrap" => out.bootstrap = cmd,
114            "build" => out.build = cmd,
115            "test" => out.test = cmd,
116            "lint" => out.lint = cmd,
117            _ => {}
118        }
119    }
120    out
121}
122
123/// Run one gate command via `sh -c` (the sanctioned shell use).
124pub fn run_gate_command(cmd: &str, cwd: &Path) -> (bool, String) {
125    let ran = gate::run_command(cmd, cwd);
126    (ran.ok(), ran.output)
127}
128
129/// What a gate established, carried from one integration to the next so
130/// that nothing is run twice on the same tree.
131#[derive(Debug, Clone, Default)]
132pub struct GateMemo {
133    /// The §5 Test command's result at a mainline commit.
134    pub suite: Option<(String, bool)>,
135    /// A mainline commit at which every Verified unit's Verification table
136    /// passed (a green gate, or a clean full audit).
137    pub tables_green_at: Option<String>,
138}
139
140/// The state of the mainline head, for the termination report.
141#[derive(Debug, Clone)]
142pub struct HeadCheck {
143    pub head: String,
144    pub findings: Vec<audit::Finding>,
145    /// A §5 Bootstrap or Build that failed at the head: (command, output).
146    pub broken: Option<(String, String)>,
147    /// The §5 Test command at the head: (command, passed, output). `None`
148    /// when the SDD has none or it was not asked for.
149    pub suite: Option<(String, bool, String)>,
150    pub interrupted: bool,
151}
152
153/// One merged member of a batch.
154struct Merged {
155    /// Index into the batch's requests.
156    i: usize,
157    branch: String,
158    merge_sha: String,
159}
160
161enum Gate {
162    Green,
163    Red { command: String, output: String },
164    Interrupted,
165}
166
167enum Suite {
168    /// No Test command, or it passed.
169    Fine(Option<bool>),
170    /// It failed after the merges and had passed before them.
171    Regressed {
172        command: String,
173        output: String,
174    },
175    Interrupted,
176}
177
178enum Final {
179    Published,
180    /// Mainline moved in substance (or a member dropped out): gate again.
181    Redo(Vec<usize>),
182    Red {
183        command: String,
184        output: String,
185    },
186    Interrupted,
187}
188
189/// A held lock on the integration checkout: one integration per repository
190/// at a time, across processes.
191struct CheckoutLock(std::fs::File);
192
193impl Drop for CheckoutLock {
194    /// Unlock before the file closes, as a temp slot does (`gate::TmpSlot`):
195    /// left to the close, the lock can outlive the integration while a child
196    /// forked meanwhile (a worker, say) has yet to exec — and the next batch
197    /// wait on it, told that another process is integrating.
198    fn drop(&mut self) {
199        let _ = self.0.unlock();
200    }
201}
202
203/// Puts the board back to `idle` however the integration it covers ends:
204/// an error, an early return or a panic leaves no stale step behind.
205struct IdleOnDrop<'a>(&'a GateBoard);
206
207impl Drop for IdleOnDrop<'_> {
208    fn drop(&mut self) {
209        self.0.idle();
210    }
211}
212
213pub struct Integrator {
214    pub ml: Mainline,
215    /// Verification rows run at once.
216    pub gate_jobs: usize,
217    /// Where the integrator says which step and commands it is running.
218    pub board: GateBoard,
219}
220
221impl Integrator {
222    pub fn new(ml: Mainline, gate_jobs: usize) -> Integrator {
223        Integrator {
224            ml,
225            gate_jobs: gate_jobs.max(1),
226            board: GateBoard::off(),
227        }
228    }
229
230    /// The integrator, reporting its progress to `board`.
231    pub fn with_board(self, board: GateBoard) -> Integrator {
232        Integrator { board, ..self }
233    }
234
235    fn checkout(&self) -> PathBuf {
236        self.ml.layout.mainline()
237    }
238
239    /// Take the integration checkout. `None` = interrupted while waiting.
240    fn lock_checkout(&self) -> Result<Option<CheckoutLock>, CoreError> {
241        let path = self.ml.layout.mainline_lock();
242        let io = |source| CoreError::Io {
243            path: path.clone(),
244            source,
245        };
246        if let Some(parent) = path.parent() {
247            std::fs::create_dir_all(parent).map_err(io)?;
248        }
249        let file = std::fs::OpenOptions::new()
250            .create(true)
251            .truncate(false)
252            .write(true)
253            .open(&path)
254            .map_err(io)?;
255        let mut told = false;
256        loop {
257            match file.try_lock() {
258                Ok(()) => return Ok(Some(CheckoutLock(file))),
259                Err(std::fs::TryLockError::WouldBlock) => {
260                    if signals::interrupted() {
261                        return Ok(None);
262                    }
263                    if !told {
264                        self.board.step("lock");
265                        diag(
266                            "note: another vitrify process is integrating in this repository — waiting for the integration checkout",
267                        );
268                        told = true;
269                    }
270                    std::thread::sleep(std::time::Duration::from_millis(250));
271                }
272                Err(std::fs::TryLockError::Error(e)) => return Err(io(e)),
273            }
274        }
275    }
276
277    /// Integrate one Built unit. `before_publish` is a test seam fired after
278    /// the gate and before the CAS/push (lost-race rehearsals).
279    pub fn integrate(
280        &self,
281        req: &IntegrateRequest,
282        memo: &mut GateMemo,
283        before_publish: Option<&dyn Fn()>,
284    ) -> Result<Outcome, CoreError> {
285        let mut out = self.integrate_batch(std::slice::from_ref(req), memo, before_publish)?;
286        Ok(out.pop().unwrap_or(Outcome::LostRace))
287    }
288
289    /// Integrate every request as one batch: one gate run for all of them.
290    /// Outcomes are index-aligned with `reqs`. A red batch of several is
291    /// integrated again one at a time.
292    pub fn integrate_batch(
293        &self,
294        reqs: &[IntegrateRequest],
295        memo: &mut GateMemo,
296        before_publish: Option<&dyn Fn()>,
297    ) -> Result<Vec<Outcome>, CoreError> {
298        let _idle = IdleOnDrop(&self.board);
299        self.board
300            .batch(reqs.iter().map(|r| r.unit.clone()).collect());
301        let mut out: Vec<Option<Outcome>> = vec![None; reqs.len()];
302        match self.lock_checkout()? {
303            Some(_held) => {
304                let all: Vec<usize> = (0..reqs.len()).collect();
305                self.run_batch(&all, reqs, &mut out, memo, before_publish)?;
306            }
307            None => out.fill(Some(Outcome::Interrupted)),
308        }
309        Ok(out
310            .into_iter()
311            .map(|o| o.unwrap_or(Outcome::LostRace))
312            .collect())
313    }
314
315    fn run_batch(
316        &self,
317        idx: &[usize],
318        reqs: &[IntegrateRequest],
319        out: &mut [Option<Outcome>],
320        memo: &mut GateMemo,
321        before_publish: Option<&dyn Fn()>,
322    ) -> Result<(), CoreError> {
323        let mlwt = self.checkout();
324        let ml = self.ml.primary.at(&mlwt);
325        let mut pending: Vec<usize> = idx.to_vec();
326        let units = |which: &[usize]| -> Vec<String> {
327            which.iter().map(|&i| reqs[i].unit.clone()).collect()
328        };
329        let interrupt = |out: &mut [Option<Outcome>], which: &[usize]| {
330            for &i in which {
331                if out[i].is_none() {
332                    out[i] = Some(Outcome::Interrupted);
333                }
334            }
335        };
336
337        for _attempt in 0..3 {
338            if signals::interrupted() {
339                interrupt(out, &pending);
340                return Ok(());
341            }
342            self.board.batch(units(&pending));
343            self.board.step("sync");
344            // 1. sync; record the CAS base. Mainline is first put right
345            // where the audit can do it mechanically, so that a lapsed lease
346            // or a spec change elsewhere is never held against this batch.
347            // A unit of the batch whose own lease has lapsed is decided
348            // before that: skipped (back to the pool), not rejected.
349            self.ml.sync_checkout(&mlwt)?;
350            let at_head = self.ml.sdd_in(&mlwt)?;
351            pending.retain(|&i| {
352                let lapsed = at_head.unit(&reqs[i].unit).is_some_and(|u| {
353                    u.meta.get_int("claim_seq") == reqs[i].token_seq
354                        && u.meta.get_str_or("status", "Draft") == "Claimed"
355                        && !UtcTime::parse(u.meta.get_str_or("claim_expires", ""))
356                            .is_some_and(|e| e > UtcTime::now())
357                });
358                if lapsed {
359                    out[i] = Some(Outcome::SkippedLeaseExpired);
360                }
361                !lapsed
362            });
363            if pending.is_empty() {
364                return Ok(());
365            }
366            match self.ml.heal(true, true) {
367                Ok(_) => {}
368                // mainline too busy to publish the housekeeping: the final
369                // audit decides whether it mattered
370                Err(e) if e.exit_code() == 5 => diag(&format!("note: {e}")),
371                Err(e) => return Err(e),
372            }
373            let base = self.ml.sync_checkout(&mlwt)?;
374
375            // 2–3. fencing, write-set, merge, input check — per unit
376            self.board.batch(units(&pending));
377            self.board.step("merge");
378            let merged = self.assemble(&ml, &mlwt, &base, &pending, reqs, out)?;
379            if merged.is_empty() {
380                return Ok(());
381            }
382            let members: Vec<usize> = merged.iter().map(|m| m.i).collect();
383            self.board.batch(units(&members));
384
385            // 4. the full integration gate, once for the batch
386            let red = |this: &Integrator,
387                       out: &mut [Option<Outcome>],
388                       memo: &mut GateMemo,
389                       command: String,
390                       output: String|
391             -> Result<(), CoreError> {
392                this.ml.checkout_at(&mlwt, &base)?;
393                if members.len() > 1 {
394                    diag(&format!(
395                        "note: gate red for a batch of {} ({command}); integrating them one at a time",
396                        members.len()
397                    ));
398                    for &i in &members {
399                        this.run_batch(&[i], reqs, out, memo, before_publish)?;
400                    }
401                } else {
402                    out[members[0]] = Some(Outcome::RejectedGate { command, output });
403                }
404                Ok(())
405            };
406            match self.gate(&mlwt, &merged, reqs)? {
407                Gate::Green => {}
408                Gate::Red { command, output } => return red(self, out, memo, command, output),
409                Gate::Interrupted => {
410                    let _ = self.ml.checkout_at(&mlwt, &base);
411                    interrupt(out, &members);
412                    return Ok(());
413                }
414            }
415            let mut rebuilt = false;
416            let suite = match self.suite(&mlwt, &base, memo, &mut rebuilt)? {
417                Suite::Fine(result) => result,
418                Suite::Regressed { command, output } => {
419                    return red(self, out, memo, command, output);
420                }
421                Suite::Interrupted => {
422                    let _ = self.ml.checkout_at(&mlwt, &base);
423                    interrupt(out, &members);
424                    return Ok(());
425                }
426            };
427
428            // 5. stamp, journal, ledger, audit, publish
429            match self.finalize(
430                &ml,
431                &mlwt,
432                &base,
433                merged,
434                rebuilt,
435                suite,
436                reqs,
437                out,
438                memo,
439                before_publish,
440            )? {
441                Final::Published => return Ok(()),
442                Final::Red { command, output } => return red(self, out, memo, command, output),
443                Final::Interrupted => {
444                    let _ = self.ml.checkout_at(&mlwt, &base);
445                    interrupt(out, &members);
446                    return Ok(());
447                }
448                Final::Redo(remaining) => {
449                    if remaining.is_empty() {
450                        return Ok(());
451                    }
452                    diag(&format!(
453                        "note: {} changed in substance during the gate; integrating again from the new head",
454                        self.ml.branch
455                    ));
456                    pending = remaining;
457                }
458            }
459        }
460        for i in pending {
461            if out[i].is_none() {
462                out[i] = Some(Outcome::LostRace);
463            }
464        }
465        Ok(())
466    }
467
468    /// Fencing check, write-set check, merge and input check for each of
469    /// `which`, on the checkout at `base`. Rejections are recorded in `out`;
470    /// the units that merged are returned in order.
471    fn assemble(
472        &self,
473        ml: &Git,
474        mlwt: &Path,
475        base: &str,
476        which: &[usize],
477        reqs: &[IntegrateRequest],
478        out: &mut [Option<Outcome>],
479    ) -> Result<Vec<Merged>, CoreError> {
480        let inst = self.ml.sdd_in(mlwt)?;
481        let slug = layout::sdd_slug(&inst);
482        let mut candidates: Vec<(usize, String)> = Vec::new();
483        for &i in which {
484            let req = &reqs[i];
485            let branch = layout::unit_branch(&slug, &req.unit, req.token_seq);
486            // fencing check FIRST, against front matter at this head
487            let Some(unit) = inst.unit(&req.unit) else {
488                out[i] = Some(Outcome::RejectedFencing {
489                    reason: format!("unit {} not found at the mainline head", req.unit),
490                });
491                continue;
492            };
493            let current_seq = unit.meta.get_int("claim_seq");
494            if req.token_seq != current_seq {
495                out[i] = Some(Outcome::RejectedFencing {
496                    reason: format!(
497                        "superseded token: branch carries c{}, current claim_seq is {}",
498                        req.token_seq, current_seq
499                    ),
500                });
501                continue;
502            }
503            match unit.meta.get_str_or("status", "Draft") {
504                "Built" => {}
505                "Claimed" => {
506                    let expires = UtcTime::parse(unit.meta.get_str_or("claim_expires", ""));
507                    if !expires.is_some_and(|e| e > UtcTime::now()) {
508                        out[i] = Some(Outcome::SkippedLeaseExpired);
509                        continue;
510                    }
511                }
512                other => {
513                    out[i] = Some(Outcome::RejectedFencing {
514                        reason: format!("unit {} is {other}, not Built/Claimed", req.unit),
515                    });
516                    continue;
517                }
518            }
519            if !ml.branch_exists(&branch).map_err(CoreError::from)? {
520                out[i] = Some(Outcome::RejectedFencing {
521                    reason: format!("work branch {branch} does not exist"),
522                });
523                continue;
524            }
525            // write-set check, before anything merges: every path the branch
526            // changed since it left mainline is owned by the unit (never a
527            // file of the SDD), or a handoff field of its own spec entry
528            let violations = write_set_violations(ml, &inst, unit, mlwt, base, &branch)?;
529            if !violations.is_empty() {
530                out[i] = Some(Outcome::RejectedWriteSet {
531                    paths: violations.iter().map(|v| v.path().to_string()).collect(),
532                    detail: violations
533                        .iter()
534                        .map(|v| v.describe(&req.unit))
535                        .collect::<Vec<_>>()
536                        .join("\n"),
537                });
538                continue;
539            }
540            // input check, still before anything merges: what the branch
541            // says the unit was built from — its Built stamp's trace — must
542            // be what mainline holds now. (It is checked again on the merged
543            // tree; here it also keeps a change to the unit's own entry on
544            // mainline from surfacing as a merge conflict in that file, when
545            // it is simply text the unit has to be rebuilt from.)
546            if let Some(outcome) = stamped_for_current_inputs(ml, &inst, unit, mlwt, &branch)? {
547                out[i] = Some(outcome);
548                continue;
549            }
550            candidates.push((i, branch));
551        }
552
553        let mut merged: Vec<Merged> = Vec::new();
554        for (i, branch) in candidates {
555            let req = &reqs[i];
556            let before = ml.rev_parse("HEAD").map_err(CoreError::from)?;
557            // merge --no-ff; never squash
558            if let Err(e) = ml.merge_no_ff(
559                &branch,
560                &format!("sdd: integrate {} (c{})", req.unit, req.token_seq),
561            ) {
562                // conflict: list conflicted paths, abort, classify
563                let conflicted = ml.conflicted_paths();
564                ml.merge_abort().map_err(CoreError::from)?;
565                ml.reset_hard(&before).map_err(CoreError::from)?;
566                if conflicted.is_empty() {
567                    return Err(e.into());
568                }
569                out[i] = Some(Outcome::OwnershipConflict { paths: conflicted });
570                continue;
571            }
572            // input check: the work must say what it was built from (the
573            // Built stamp's trace), and that must be what mainline holds now
574            let merged_inst = self.ml.sdd_in(mlwt)?;
575            let rejected = match merged_inst.unit(&req.unit) {
576                None => Some(Outcome::RejectedFencing {
577                    reason: format!("unit {} missing after merge", req.unit),
578                }),
579                Some(unit) => built_from_current_inputs(&merged_inst, unit)?,
580            };
581            if let Some(outcome) = rejected {
582                ml.reset_hard(&before).map_err(CoreError::from)?;
583                out[i] = Some(outcome);
584                continue;
585            }
586            merged.push(Merged {
587                i,
588                branch,
589                merge_sha: ml.rev_parse("HEAD").map_err(CoreError::from)?,
590            });
591        }
592        Ok(merged)
593    }
594
595    /// Bootstrap, Build, the Verification tables and Lint, on the merged
596    /// tree.
597    fn gate(
598        &self,
599        mlwt: &Path,
600        merged: &[Merged],
601        reqs: &[IntegrateRequest],
602    ) -> Result<Gate, CoreError> {
603        let inst = self.ml.sdd_in(mlwt)?;
604        let cmds = sdd_commands(&model::read_text(&inst.file)?);
605        let verdict = |command: &str, ran: Ran| {
606            if ran.interrupted || signals::interrupted() {
607                Gate::Interrupted
608            } else {
609                Gate::Red {
610                    command: command.to_string(),
611                    output: ran.output,
612                }
613            }
614        };
615        for (step, cmd) in [("bootstrap", &cmds.bootstrap), ("build", &cmds.build)] {
616            let Some(cmd) = cmd else { continue };
617            self.board.step(step);
618            let ran = gate::run_command_watched(cmd, mlwt, &self.board);
619            if !ran.ok() {
620                return Ok(verdict(cmd, ran));
621            }
622        }
623        // the batch's own tables, then every Verified unit's — where
624        // semantic conflicts between units surface; each distinct command
625        // runs once
626        let mut rows: Vec<String> = Vec::new();
627        let batch: Vec<&str> = merged.iter().map(|m| reqs[m.i].unit.as_str()).collect();
628        let mut add = |unit: &model::Unit| -> Result<(), CoreError> {
629            for cmd in gate::verification_table(&inst, unit)? {
630                if !rows.contains(&cmd) {
631                    rows.push(cmd);
632                }
633            }
634            Ok(())
635        };
636        for uid in &batch {
637            if let Some(unit) = inst.unit(uid) {
638                add(unit)?;
639            }
640        }
641        for unit in &inst.units {
642            if !batch.contains(&unit.unit.as_str())
643                && unit.meta.get_str_or("status", "Draft") == "Verified"
644            {
645                add(unit)?;
646            }
647        }
648        self.board.step("rows");
649        self.board.rows(rows.len());
650        let results = gate::run_rows_watched(&rows, mlwt, self.gate_jobs, true, &self.board);
651        for (cmd, ran) in rows.iter().zip(results) {
652            if let Some(ran) = ran
653                && !ran.ok()
654            {
655                return Ok(verdict(cmd, ran));
656            }
657        }
658        if signals::interrupted() {
659            return Ok(Gate::Interrupted);
660        }
661        if let Some(cmd) = &cmds.lint {
662            self.board.step("lint");
663            let ran = gate::run_command_watched(cmd, mlwt, &self.board);
664            if !ran.ok() {
665                return Ok(verdict(cmd, ran));
666            }
667        }
668        Ok(Gate::Green)
669    }
670
671    /// The §5 Test command on the merged tree: the whole suite, which
672    /// Verification rows — each selecting a few tests — cannot stand in for.
673    /// It gates as a regression check: a merge must not turn it from passing
674    /// to failing. While it already fails at the head (no tests yet, tests
675    /// awaiting their code, an earlier breakage) no merge is judged by it.
676    /// Its state before the merges is taken from `memo`, or measured at
677    /// `base` — which resets the checkout (`rebuilt`).
678    fn suite(
679        &self,
680        mlwt: &Path,
681        base: &str,
682        memo: &mut GateMemo,
683        rebuilt: &mut bool,
684    ) -> Result<Suite, CoreError> {
685        let inst = self.ml.sdd_in(mlwt)?;
686        let cmds = sdd_commands(&model::read_text(&inst.file)?);
687        let Some(test) = cmds.test.clone() else {
688            return Ok(Suite::Fine(None));
689        };
690        self.board.step("test");
691        let after = gate::run_command_watched(&test, mlwt, &self.board);
692        if after.interrupted || signals::interrupted() {
693            return Ok(Suite::Interrupted);
694        }
695        if after.ok() {
696            return Ok(Suite::Fine(Some(true)));
697        }
698        let before = match self.suite_known(memo, base)? {
699            Some(passed) => passed,
700            None => {
701                // measure at the base: the tree as it was before the merges
702                self.board.step("test-base");
703                self.ml.checkout_at(mlwt, base)?;
704                *rebuilt = true;
705                let mut passed = true;
706                for cmd in [&cmds.bootstrap, &cmds.build, &Some(test.clone())]
707                    .into_iter()
708                    .flatten()
709                {
710                    let ran = gate::run_command_watched(cmd, mlwt, &self.board);
711                    if ran.interrupted || signals::interrupted() {
712                        return Ok(Suite::Interrupted);
713                    }
714                    if !ran.ok() {
715                        passed = false;
716                        break;
717                    }
718                }
719                memo.suite = Some((base.to_string(), passed));
720                passed
721            }
722        };
723        if before {
724            Ok(Suite::Regressed {
725                command: test,
726                output: format!(
727                    "{}\n(the §5 Test command passed before this merge and fails after it)",
728                    after.output
729                ),
730            })
731        } else {
732            diag(&format!(
733                "note: the §5 Test command already fails at the {} head — integrations are not judged by it until it passes: {test}",
734                self.ml.branch
735            ));
736            Ok(Suite::Fine(Some(false)))
737        }
738    }
739
740    /// The Test command's result at `commit`, if `memo` holds one that
741    /// still applies.
742    fn suite_known(&self, memo: &GateMemo, commit: &str) -> Result<Option<bool>, CoreError> {
743        match &memo.suite {
744            Some((at, passed)) if benign(&self.ml, at, commit)? => Ok(Some(*passed)),
745            _ => Ok(None),
746        }
747    }
748
749    /// Steps 5–6: on the gated tree, stamp every unit Verified, append the
750    /// journal events, regenerate the ledger, require a clean audit, commit
751    /// and publish. If mainline moved since the gate started, the gate's
752    /// verdict still stands when the commits in between moved nothing but
753    /// protocol state (claims, renewals, releases, recorded questions): the
754    /// merges are then replayed on the new head and published from there.
755    #[allow(clippy::too_many_arguments)]
756    fn finalize(
757        &self,
758        ml: &Git,
759        mlwt: &Path,
760        gated_base: &str,
761        mut merged: Vec<Merged>,
762        mut rebuild: bool,
763        suite: Option<bool>,
764        reqs: &[IntegrateRequest],
765        out: &mut [Option<Outcome>],
766        memo: &mut GateMemo,
767        before_publish: Option<&dyn Fn()>,
768    ) -> Result<Final, CoreError> {
769        let mut base = gated_base.to_string();
770        let mut heals_left = 2;
771        for _ in 0..6 {
772            self.board.step("publish");
773            if signals::interrupted() {
774                return Ok(Final::Interrupted);
775            }
776            // this process's other mainline writers wait their turn from here
777            let turn = claim::tx_lock();
778            let head = self.ml.head()?;
779            if head != base {
780                if !self.benign(gated_base, &head)? {
781                    return Ok(Final::Redo(merged.iter().map(|m| m.i).collect()));
782                }
783                rebuild = true;
784            }
785            if rebuild {
786                self.ml.checkout_at(mlwt, &head)?;
787                let before: Vec<usize> = merged.iter().map(|m| m.i).collect();
788                merged = self.assemble(ml, mlwt, &head, &before, reqs, out)?;
789                if merged.len() != before.len() {
790                    // a member dropped out: the gated tree is not this tree
791                    self.ml.checkout_at(mlwt, &head)?;
792                    return Ok(Final::Redo(merged.iter().map(|m| m.i).collect()));
793                }
794                base = head.clone();
795            }
796            // What is stamped, audited and published is the merged tree and
797            // nothing else. Whatever the gate's commands left in the
798            // checkout — files they wrote, tracked files they rewrote — goes
799            // here, so the result never depends on whether the merges had
800            // to be replayed.
801            ml.reset_hard("HEAD").map_err(CoreError::from)?;
802            ml.clean_fdq().map_err(CoreError::from)?;
803
804            let inst = self.ml.sdd_in(mlwt)?;
805            for m in &merged {
806                let req = &reqs[m.i];
807                let Some(unit) = inst.unit(&req.unit) else {
808                    continue;
809                };
810                stamp_verified(&inst, unit, short(&m.merge_sha))?;
811                let branch_sha = ml.rev_parse(&m.branch).map_err(CoreError::from)?;
812                for (event, actor, commit) in [
813                    ("built", &req.builder_holder, short(&branch_sha)),
814                    ("verified", &req.integrator_id, short(&m.merge_sha)),
815                ] {
816                    append_event(
817                        &inst,
818                        Event {
819                            event: event.to_string(),
820                            unit: Some(req.unit.clone()),
821                            actor: Some(actor.clone()),
822                            claim_seq: Some(req.token_seq),
823                            commit: Some(commit.to_string()),
824                            ..Default::default()
825                        },
826                    )?;
827                }
828            }
829            let stamped = self.ml.sdd_in(mlwt)?;
830            ledger::regen(&stamped, &UtcTime::now().format_date())?;
831            // audit --skip-rotten --journal: must be clean, run last on the
832            // stamped tree (checks 1–3 on what the merges brought in; 5–7 on
833            // the state about to be published)
834            let (findings, _) = audit::run(
835                &stamped,
836                mlwt,
837                &cmd::audit_options(
838                    audit::Options {
839                        skip_rotten: true,
840                        ..Default::default()
841                    },
842                    mlwt,
843                    &stamped,
844                ),
845                &ShRunner,
846                UtcTime::now(),
847            )?;
848            // A lease this run does not hold that lapsed since the sync, or
849            // a trace elsewhere that a change on mainline staled: mainline's
850            // own state, and mechanically put right — not a verdict on this
851            // batch. Put it right and publish from the new head.
852            let batch: Vec<&str> = merged.iter().map(|m| reqs[m.i].unit.as_str()).collect();
853            let elsewhere = |f: &audit::Finding| {
854                matches!(f.check, 5 | 7) && !batch.contains(&f.subject.as_str())
855            };
856            if !findings.is_empty() && findings.iter().all(elsewhere) {
857                drop(turn);
858                if heals_left == 0 {
859                    self.ml.checkout_at(mlwt, &base)?;
860                    return Ok(Final::Redo(merged.iter().map(|m| m.i).collect()));
861                }
862                heals_left -= 1;
863                match self.ml.heal(true, true) {
864                    Ok(_) => {}
865                    Err(e) if e.exit_code() == 5 => diag(&format!("note: {e}")),
866                    Err(e) => return Err(e),
867                }
868                rebuild = true;
869                continue;
870            }
871            if !findings.is_empty() {
872                drop(turn);
873                self.ml.checkout_at(mlwt, &base)?;
874                return Ok(Final::Red {
875                    command: "vitrify audit --skip-rotten --journal".to_string(),
876                    output: findings
877                        .iter()
878                        .map(|f| format!("[check {}] {}: {}", f.check, f.subject, f.cause))
879                        .collect::<Vec<_>>()
880                        .join("\n"),
881                });
882            }
883            append_event(
884                &stamped,
885                Event {
886                    event: "audit".to_string(),
887                    actor: Some("audit".to_string()),
888                    findings: Some(0),
889                    ..Default::default()
890                },
891            )?;
892            ml.add_all().map_err(CoreError::from)?;
893            let label = merged
894                .iter()
895                .map(|m| format!("{} (c{})", reqs[m.i].unit, reqs[m.i].token_seq))
896                .collect::<Vec<_>>()
897                .join(", ");
898            ml.commit(&format!("sdd: verify {label}"))
899                .map_err(CoreError::from)?;
900            let verify_sha = ml.rev_parse("HEAD").map_err(CoreError::from)?;
901
902            if let Some(hook) = before_publish {
903                hook();
904            }
905            if signals::interrupted() {
906                return Ok(Final::Interrupted);
907            }
908
909            // publish every merge and the verify commit as one move
910            if let Some(landed) = self.ml.publish(&verify_sha, &base)? {
911                self.ml.follow(&landed)?;
912                drop(turn);
913                memo.tables_green_at = Some(verify_sha.clone());
914                if let Some(passed) = suite {
915                    memo.suite = Some((verify_sha.clone(), passed));
916                }
917                let slug = layout::sdd_slug(&stamped);
918                for m in &merged {
919                    let req = &reqs[m.i];
920                    // the merged attempt's worktree and branch are done
921                    let wt = self
922                        .ml
923                        .layout
924                        .unit_worktree(&slug, &req.unit, req.token_seq);
925                    if wt.exists() {
926                        let _ = self.ml.primary.worktree_remove(&wt);
927                    }
928                    self.ml
929                        .primary
930                        .delete_branch(&m.branch)
931                        .map_err(CoreError::from)?;
932                    out[m.i] = Some(Outcome::Verified {
933                        merge_commit: m.merge_sha.clone(),
934                        verify_commit: verify_sha.clone(),
935                    });
936                }
937                return Ok(Final::Published);
938            }
939            drop(turn);
940            diag(&format!(
941                "note: lost publish race integrating {label} on {}; redoing from sync",
942                self.ml.branch
943            ));
944            rebuild = true;
945        }
946        Ok(Final::Redo(merged.iter().map(|m| m.i).collect()))
947    }
948
949    /// [`benign`] for this integrator's repository.
950    pub fn benign(&self, old: &str, new: &str) -> Result<bool, CoreError> {
951        benign(&self.ml, old, new)
952    }
953
954    /// The mainline head as the termination report needs it: the audit
955    /// (check 4 skipped when `memo` shows every Verified table green on
956    /// this tree) and, when `want_suite`, the §5 Test command.
957    pub fn check_head(
958        &self,
959        memo: &mut GateMemo,
960        want_suite: bool,
961    ) -> Result<HeadCheck, CoreError> {
962        let mlwt = self.checkout();
963        let _idle = IdleOnDrop(&self.board);
964        self.board.batch(Vec::new());
965        let Some(_held) = self.lock_checkout()? else {
966            return Ok(HeadCheck {
967                head: String::new(),
968                findings: Vec::new(),
969                broken: None,
970                suite: None,
971                interrupted: true,
972            });
973        };
974        self.board.step("head-check");
975        let head = self.ml.sync_checkout(&mlwt)?;
976        let inst = self.ml.sdd_in(&mlwt)?;
977        let cmds = sdd_commands(&model::read_text(&inst.file)?);
978        let mut check = HeadCheck {
979            head: head.clone(),
980            findings: Vec::new(),
981            broken: None,
982            suite: None,
983            interrupted: false,
984        };
985
986        let tables_known = match &memo.tables_green_at {
987            Some(at) => self.benign(at, &head)?,
988            None => false,
989        };
990        let suite_known = self.suite_known(memo, &head)?;
991        let run_suite = want_suite && cmds.test.is_some() && suite_known.is_none();
992        // commands are about to run here: the environment first
993        if !tables_known || run_suite {
994            for cmd in [&cmds.bootstrap, &cmds.build].into_iter().flatten() {
995                let ran = gate::run_command_watched(cmd, &mlwt, &self.board);
996                if ran.interrupted || signals::interrupted() {
997                    check.interrupted = true;
998                    return Ok(check);
999                }
1000                if !ran.ok() {
1001                    check.broken = Some((cmd.clone(), ran.output));
1002                    return Ok(check);
1003                }
1004            }
1005        }
1006        let options = |skip_rotten| {
1007            cmd::audit_options(
1008                audit::Options {
1009                    skip_rotten,
1010                    ..Default::default()
1011                },
1012                &mlwt,
1013                &inst,
1014            )
1015        };
1016        let (findings, _) = if tables_known {
1017            audit::run(&inst, &mlwt, &options(true), &ShRunner, UtcTime::now())?
1018        } else {
1019            self.board.rows(gate::verified_commands(&inst)?.len());
1020            let runner =
1021                gate::MemoRunner::for_verified_watched(&inst, &mlwt, self.gate_jobs, &self.board)?;
1022            audit::run(&inst, &mlwt, &options(false), &runner, UtcTime::now())?
1023        };
1024        if signals::interrupted() {
1025            check.interrupted = true;
1026            return Ok(check);
1027        }
1028        if findings.is_empty() {
1029            memo.tables_green_at = Some(head.clone());
1030        }
1031        check.findings = findings;
1032
1033        if want_suite && let Some(test) = &cmds.test {
1034            check.suite = Some(match suite_known {
1035                Some(passed) => (test.clone(), passed, String::new()),
1036                None => {
1037                    let ran = gate::run_command_watched(test, &mlwt, &self.board);
1038                    if ran.interrupted || signals::interrupted() {
1039                        check.interrupted = true;
1040                        return Ok(check);
1041                    }
1042                    memo.suite = Some((head.clone(), ran.ok()));
1043                    (test.clone(), ran.ok(), ran.output)
1044                }
1045            });
1046        }
1047        Ok(check)
1048    }
1049}
1050
1051/// Changed paths between two commits, each with whether it is protocol
1052/// state only: a journal, a ledger, a decision or change log, or a unit
1053/// entry that differs in nothing but its vitrify-managed fields.
1054fn classify_changes(ml: &Mainline, old: &str, new: &str) -> Result<Vec<(String, bool)>, CoreError> {
1055    let git = &ml.primary;
1056    // a single-file SDD is its own path, whatever the file is called
1057    let own = cmd::sdd_arg(&ml.sdd_rel);
1058    let mut bundles: Vec<(String, bool)> = Vec::new();
1059    let mut is_bundle = |dir: &str| -> bool {
1060        if let Some((_, known)) = bundles.iter().find(|(d, _)| d == dir) {
1061            return *known;
1062        }
1063        let core = if dir.is_empty() {
1064            "sdd.md".to_string()
1065        } else {
1066            format!("{dir}/sdd.md")
1067        };
1068        let known = git
1069            .show_text(new, &core)
1070            .ok()
1071            .flatten()
1072            .and_then(|t| model::front_matter(&t))
1073            .is_some_and(|m| m.has("sdd"));
1074        bundles.push((dir.to_string(), known));
1075        known
1076    };
1077    let both = |path: &str| -> Option<(String, String)> {
1078        Some((
1079            git.show_text(old, path).ok().flatten()?,
1080            git.show_text(new, path).ok().flatten()?,
1081        ))
1082    };
1083    let mut out = Vec::new();
1084    for path in git.changed_paths(old, new).map_err(CoreError::from)? {
1085        let (dir, name) = path.rsplit_once('/').unwrap_or(("", path.as_str()));
1086        let state_only = if matches!(
1087            name,
1088            "journal.ndjson" | "ledger.md" | "decisions.md" | "changelog.md"
1089        ) {
1090            is_bundle(dir)
1091        } else if name.ends_with(".sdd.md") || path == own {
1092            both(&path).is_some_and(|(a, b)| single_state_masked(&a) == single_state_masked(&b))
1093        } else if (dir == "units" || dir.ends_with("/units"))
1094            && name.starts_with("U-")
1095            && name.ends_with(".md")
1096            && is_bundle(dir.trim_end_matches("units").trim_end_matches('/'))
1097        {
1098            both(&path).is_some_and(|(a, b)| {
1099                trace::mask_unit_fields(Shape::Bundle, &a, "", &trace::VOLATILE)
1100                    == trace::mask_unit_fields(Shape::Bundle, &b, "", &trace::VOLATILE)
1101            })
1102        } else {
1103            false
1104        };
1105        out.push((path, state_only));
1106    }
1107    Ok(out)
1108}
1109
1110/// Whether `old..new` moved nothing but protocol state: journals, ledgers,
1111/// decision and change logs, and the vitrify-managed fields of unit
1112/// entries. Such commits — claims, renewals, releases, recorded questions —
1113/// change nothing a build, a test or a lint reads, so what a gate
1114/// established at `old` holds at `new`.
1115pub fn benign(ml: &Mainline, old: &str, new: &str) -> Result<bool, CoreError> {
1116    if old == new {
1117        return Ok(true);
1118    }
1119    if !ml.primary.is_ancestor(old, new).map_err(CoreError::from)? {
1120        return Ok(false);
1121    }
1122    Ok(classify_changes(ml, old, new)?
1123        .iter()
1124        .all(|(_, state_only)| *state_only))
1125}
1126
1127/// Whether `old..new` changed the SDD's own text — anything under its root
1128/// beyond protocol state. Only then can a recorded trace have gone stale.
1129pub fn spec_moved(ml: &Mainline, old: &str, new: &str) -> Result<bool, CoreError> {
1130    if old == new {
1131        return Ok(false);
1132    }
1133    if !ml.primary.is_ancestor(old, new).map_err(CoreError::from)? {
1134        return Ok(true);
1135    }
1136    let root = cmd::sdd_arg(&ml.sdd_rel);
1137    let under = |p: &str| root == "." || p == root || p.starts_with(&format!("{root}/"));
1138    Ok(classify_changes(ml, old, new)?
1139        .iter()
1140        .any(|(path, state_only)| under(path) && !state_only))
1141}
1142
1143fn short(sha: &str) -> &str {
1144    &sha[..7.min(sha.len())]
1145}
1146
1147/// A single-file SDD's text with everything vitrify itself writes removed:
1148/// each unit's managed fields, the journal, the ledger, the decision and
1149/// change logs.
1150fn single_state_masked(text: &str) -> String {
1151    let mut t = text.to_string();
1152    let ids: Vec<String> = model::split_h3_regions(&t, "Work Units")
1153        .into_iter()
1154        .map(|(id, _)| id)
1155        .collect();
1156    for id in ids {
1157        if let Some(masked) = trace::mask_unit_fields(Shape::Single, &t, &id, &trace::VOLATILE) {
1158            t = masked;
1159        }
1160    }
1161    for heading in [
1162        "Journal",
1163        "State Ledger",
1164        "Decisions & Open Questions",
1165        "Changelog",
1166    ] {
1167        if let Some((s, e)) = model::section_span(&t, heading) {
1168            t = format!("{}{}", &t[..s], &t[e..]);
1169        }
1170    }
1171    t
1172}
1173
1174/// A unit's front matter as `text` — its unit file, or the single-file SDD
1175/// holding its region — has it.
1176fn unit_meta_in(shape: Shape, text: &str, uid: &str) -> Option<model::Meta> {
1177    match shape {
1178        Shape::Bundle => model::front_matter(text),
1179        Shape::Single => {
1180            let (start, end) = model::find_unit_span(text, uid)?;
1181            let region = &text[start..end];
1182            let (_, _, inner_start, inner_end) = model::find_meta_block_span(region)?;
1183            Some(model::Meta(yamlish::parse(&region[inner_start..inner_end])))
1184        }
1185    }
1186}
1187
1188/// The input check before the merge: `None` when the unit's entry on
1189/// `branch` is stamped Built with a trace equal to what its inputs hash to
1190/// at the head (`inst`, loaded from the checkout at `root`). The write-set
1191/// check has passed, so the branch changed nothing of that entry but the
1192/// handoff fields.
1193fn stamped_for_current_inputs(
1194    ml: &Git,
1195    inst: &Instance,
1196    unit: &model::Unit,
1197    root: &Path,
1198    branch: &str,
1199) -> Result<Option<Outcome>, CoreError> {
1200    let spec_file = WriteSet::of(inst, unit, root)?.spec_file;
1201    let stamped = ml
1202        .show_text(branch, &spec_file)
1203        .map_err(CoreError::from)?
1204        .and_then(|text| unit_meta_in(inst.shape, &text, &unit.unit))
1205        .unwrap_or_default();
1206    judge_stamp(inst, unit, &stamped)
1207}
1208
1209/// The input check: `None` when the merged unit is stamped Built with a
1210/// trace equal to what its inputs hash to now.
1211fn built_from_current_inputs(
1212    merged: &Instance,
1213    unit: &model::Unit,
1214) -> Result<Option<Outcome>, CoreError> {
1215    judge_stamp(merged, unit, &unit.meta)
1216}
1217
1218/// `stamped` (a version of `unit`'s front matter) against the unit's inputs
1219/// as `inst` holds them.
1220fn judge_stamp(
1221    inst: &Instance,
1222    unit: &model::Unit,
1223    stamped: &model::Meta,
1224) -> Result<Option<Outcome>, CoreError> {
1225    let merged = inst;
1226    let status = stamped.get_str_or("status", "Draft");
1227    let recorded = stamped.get_map("trace").cloned().unwrap_or_default();
1228    if status != "Built" || recorded.is_empty() {
1229        return Ok(Some(Outcome::RejectedNotBuilt {
1230            reason: format!(
1231                "the work does not stamp {} Built (status {status}{}) — `vitrify trace record --stamp built` is the handoff",
1232                unit.unit,
1233                if recorded.is_empty() {
1234                    ", no trace"
1235                } else {
1236                    ""
1237                }
1238            ),
1239        }));
1240    }
1241    let (current, problems) = trace::compute(merged, unit)?;
1242    if !problems.is_empty() {
1243        return Err(CoreError::refusal(
1244            4,
1245            problems
1246                .iter()
1247                .map(|p| format!("error: {p}"))
1248                .collect::<Vec<_>>()
1249                .join("\n"),
1250        ));
1251    }
1252    let mismatches = trace::verify(&recorded, &current);
1253    if mismatches.is_empty() {
1254        Ok(None)
1255    } else {
1256        Ok(Some(Outcome::RejectedStaleInputs {
1257            keys: mismatches.into_iter().map(|m| m.key).collect(),
1258        }))
1259    }
1260}
1261
1262/// The write-set check (schema §13.3): classify every path the branch changed
1263/// since it forked from `base` against the unit's write-set as defined at
1264/// `base`. Empty = the work stays inside what the unit may write.
1265fn write_set_violations(
1266    ml: &Git,
1267    inst: &Instance,
1268    unit: &model::Unit,
1269    root: &Path,
1270    base: &str,
1271    branch: &str,
1272) -> Result<Vec<Violation>, CoreError> {
1273    let ws = WriteSet::of(inst, unit, root)?;
1274    let fork = ml.merge_base(base, branch).map_err(CoreError::from)?;
1275    let changed = ml.changed_paths(&fork, branch).map_err(CoreError::from)?;
1276    let spec_file = ws.spec_file.clone();
1277    let versions = || {
1278        (
1279            ml.show_text(&fork, &spec_file).ok().flatten(),
1280            ml.show_text(branch, &spec_file).ok().flatten(),
1281        )
1282    };
1283    Ok(ws.violations(&changed, versions))
1284}
1285
1286/// `trace record --stamp verified --commit <sha>` via core (one hashing
1287/// implementation; this is wiring, not a second recipe).
1288fn stamp_verified(inst: &Instance, unit: &model::Unit, commit: &str) -> Result<(), CoreError> {
1289    let (trace_map, problems) = trace::compute(inst, unit)?;
1290    if !problems.is_empty() {
1291        return Err(CoreError::refusal(
1292            4,
1293            problems
1294                .iter()
1295                .map(|p| format!("error: {p}"))
1296                .collect::<Vec<_>>()
1297                .join("\n"),
1298        ));
1299    }
1300    let stamp = model::render_stamp(
1301        &UtcTime::now().format_date(),
1302        inst.meta.get_str_or("version", "0.0.0"),
1303        commit,
1304    );
1305    model::rewrite_unit_meta(&inst.handle(), unit, |inner| {
1306        let b = yamlish::set_scalar_in_place(inner, "status", "Verified");
1307        let b = yamlish::set_scalar_in_place(&b, "verified", &stamp);
1308        let b = yamlish::set_scalar_in_place(&b, "claimed_by", "—");
1309        let b = yamlish::set_scalar_in_place(&b, "claim_expires", "—");
1310        yamlish::set_map_in_place(&b, "trace", &trace_map)
1311    })?;
1312    Ok(())
1313}