Skip to main content

vitrify_cli/run/
integrate.rs

1//! A lane's serial integrator: every Built unit of its SDD that is ready, as
2//! one batch, in the lane's own integration checkout. Fencing check first;
3//! then the 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 tables of
12//! the units being integrated and of the SDD's **dirty** Verified units —
13//! those a path they are checked against changed since their last recorded
14//! check, every dependent of the merged units among them — each distinct
15//! command once, `run.gate_jobs` at a time ([`rows::for_gate`]); the §5
16//! Lint command; then the §5 Test command — the whole suite, which a merge
17//! must not turn from passing to failing — and audit checks 1–3. Rows of
18//! clean units are not run: their recorded checks hold. An SDD without a
19//! Test command has no backstop for what its declarations miss, so its gate
20//! runs every Verified unit's rows. The integration commit records the
21//! re-checks the gate made (a `verified` event with actor `recheck` and a
22//! fresh stamp for each dirty unit whose rows passed) and `suite: "pass"`
23//! when the Test command passed, so a later run trusts them.
24//!
25//! A lane that loses the publish race does not always gate again. The
26//! commits it lost to are replayed over when, beyond protocol state, they
27//! changed nothing its gate checked or read ([`Footprint`]): no file of a
28//! unit whose rows ran or of anything those units depend on, none of its
29//! SDD's unmanaged files, no path outside every scope the SDD takes as
30//! input, and — when the gate ran the §5 Test command — nothing in its
31//! SDD's scope at all. The merges are then replayed on the new head, the
32//! fencing, write-set and input checks made again there, and the result
33//! published without another gate.
34//!
35//! No new failures: a failing row of a unit already Verified (and not in
36//! the batch) is run again on the base, in the lane's own pristine base
37//! checkout ([`blame::judge`]). A row that passes there was broken by the
38//! batch, which is rejected. A row that fails there too was broken before
39//! the batch: its unit is **rotten**, the batch is judged on its other rows,
40//! and the rotten unit's rows are left out of the lane's later gates until
41//! the scheduler says otherwise ([`Integrator::forget_rotten`]). A failing
42//! row of the batch's own units is always the batch's.
43
44use std::collections::{BTreeMap, BTreeSet};
45use std::path::{Path, PathBuf};
46use std::sync::Mutex;
47
48use vitrify_core::audit;
49use vitrify_core::cascade::{Owner, Ownership};
50use vitrify_core::graph::{self as unit_graph, Node};
51use vitrify_core::journal::{self, Event};
52use vitrify_core::model::{self, Instance, Shape, UtcTime};
53use vitrify_core::writeset::{Violation, WriteSet};
54use vitrify_core::{CoreError, ledger, trace, yamlish};
55
56use super::mainline::{LaneLock, Mainline, append_event};
57use super::progress::GateBoard;
58use crate::cmd::{self, claim};
59use crate::gate::{self, Ran, ShRunner};
60use crate::git::Git;
61use crate::incremental::blame::{self, Judged, PristineCheckout, ShellRunner};
62use crate::incremental::dirty::{self, Cascade, DiffCache, Mode, Snapshot, SpecFiles};
63use crate::incremental::{recheck, rows};
64use crate::layout;
65use crate::out::diag;
66use crate::signals;
67
68pub struct IntegrateRequest {
69    pub unit: String,
70    pub token_seq: i64,
71    pub builder_holder: String,
72    pub integrator_id: String,
73}
74
75#[derive(Debug, Clone)]
76pub enum Outcome {
77    Verified {
78        merge_commit: String,
79        verify_commit: String,
80    },
81    /// Superseded token or wrong state — rejected outright, tests not run.
82    RejectedFencing { reason: String },
83    /// Token current but the lease merely expired at gate start: not an
84    /// error — the unit returns to the pool.
85    SkippedLeaseExpired,
86    /// The branch changed paths outside the unit's write-set (schema §13.3):
87    /// files the unit does not own (`unmanaged` ones included), other files
88    /// of the SDD, or its own spec text beyond the handoff fields. Rejected
89    /// before merging — nothing merged, nothing published. `detail` holds
90    /// one line per violation.
91    RejectedWriteSet { paths: Vec<String>, detail: String },
92    /// The work does not stamp the unit Built with a recorded trace: there
93    /// is nothing to say what it was built from.
94    RejectedNotBuilt { reason: String },
95    /// The trace the unit was built from no longer matches the spec text at
96    /// the mainline head: an input (`keys`) changed while it was being
97    /// built. Not the work's fault — the unit is rebuilt from current text.
98    RejectedStaleInputs { keys: Vec<String> },
99    /// Gate red: reverted to the recorded base; nothing published.
100    RejectedGate { command: String, output: String },
101    /// Merge conflict. The write-set check already passed, so every
102    /// conflicted path is one this unit may write that mainline also changed
103    /// after the branch forked — treated as an ownership violation: escalate.
104    OwnershipConflict { paths: Vec<String> },
105    /// CAS/push lost after the retry budget.
106    LostRace,
107    /// The run was interrupted before this unit's integration finished;
108    /// nothing was published.
109    Interrupted,
110}
111
112/// The SDD §5 Commands block (`### Commands` in the core file). `vitrify run`
113/// preflight runs bootstrap, build and lint; the integration gate runs all
114/// four — `test` as a regression check (see [`Integrator`]).
115#[derive(Debug, Clone, Default)]
116pub struct SddCommands {
117    pub bootstrap: Option<String>,
118    pub build: Option<String>,
119    pub test: Option<String>,
120    pub lint: Option<String>,
121}
122
123pub fn sdd_commands(core_text: &str) -> SddCommands {
124    // one parser for §5 Commands: what the gate runs is what a re-check runs
125    let c = crate::incremental::rows::Commands::parse(core_text);
126    SddCommands {
127        bootstrap: c.bootstrap,
128        build: c.build,
129        test: c.test,
130        lint: c.lint,
131    }
132}
133
134/// Run one gate command via `sh -c` (the sanctioned shell use).
135pub fn run_gate_command(cmd: &str, cwd: &Path) -> (bool, String) {
136    let ran = gate::run_command(cmd, cwd);
137    (ran.ok(), ran.output)
138}
139
140/// What a gate established, carried from one integration to the next so
141/// that nothing is run twice on the same tree.
142#[derive(Debug, Clone, Default)]
143pub struct GateMemo {
144    /// The §5 Test command's result at a mainline commit.
145    pub suite: Option<(String, bool)>,
146}
147
148/// The state of the mainline head, for the termination report.
149#[derive(Debug, Clone)]
150pub struct HeadCheck {
151    pub head: String,
152    pub findings: Vec<audit::Finding>,
153    /// A §5 Bootstrap or Build that failed at the head: (command, output).
154    pub broken: Option<(String, String)>,
155    /// The §5 Test command at the head: (command, passed, output). `None`
156    /// when the SDD has none or it was not asked for.
157    pub suite: Option<(String, bool, String)>,
158    pub interrupted: bool,
159}
160
161/// One merged member of a batch.
162struct Merged {
163    /// Index into the batch's requests.
164    i: usize,
165    branch: String,
166    merge_sha: String,
167}
168
169enum Gate {
170    /// Every selected row passed (or was found rotten): the dirty Verified
171    /// units whose rows passed, to be recorded as re-checked, and what the
172    /// gate checked or read.
173    Green {
174        rechecked: Vec<String>,
175        footprint: Option<Footprint>,
176    },
177    Red {
178        command: String,
179        output: String,
180    },
181    Interrupted,
182}
183
184enum Suite {
185    /// No Test command, or it passed.
186    Fine(Option<bool>),
187    /// It failed after the merges and had passed before them.
188    Regressed {
189        command: String,
190        output: String,
191    },
192    Interrupted,
193}
194
195enum Final {
196    Published,
197    /// Mainline moved in substance (or a member dropped out): gate again.
198    Redo(Vec<usize>),
199    Red {
200        command: String,
201        output: String,
202    },
203    Interrupted,
204}
205
206/// Puts the board back to `idle` however the integration it covers ends:
207/// an error, an early return or a panic leaves no stale step behind.
208struct IdleOnDrop<'a>(&'a GateBoard);
209
210impl Drop for IdleOnDrop<'_> {
211    fn drop(&mut self) {
212        self.0.idle();
213    }
214}
215
216/// How many times a publish is built and tried before the batch is gated
217/// again: a lost race costs a replay, not a gate, while the commits that
218/// won it leave the verdict standing.
219const PUBLISH_TRIES: usize = 12;
220
221/// A Verification row that failed at a gate and on its base too: its unit
222/// is rotten.
223#[derive(Debug, Clone, PartialEq, Eq)]
224pub struct RottenRow {
225    pub unit: String,
226    /// The row's 1-based position in the unit's Verification table.
227    pub row_number: usize,
228    pub row: String,
229    /// The commit the batch was merged onto, where the row failed too.
230    pub base: String,
231    /// The tail of the row's output at the gate.
232    pub output: String,
233}
234
235pub struct Integrator {
236    pub ml: Mainline,
237    /// Verification rows run at once.
238    pub gate_jobs: usize,
239    /// Where the integrator says which step and commands it is running.
240    pub board: GateBoard,
241    /// Rotten rows found since the last [`Integrator::take_rotten`], when
242    /// no sink takes them as they are found.
243    found: Mutex<Vec<RottenRow>>,
244    /// Told of rotten rows the moment they are found — before anything is
245    /// published — so the units that depend on them are never dispatched
246    /// against a head that already holds the verdict's batch.
247    rotten_sink: Option<Box<dyn Fn(Vec<RottenRow>) + Send>>,
248    /// Units held rotten: their rows are left out of later gates.
249    held: Mutex<BTreeSet<String>>,
250    /// What the dirty sets of earlier gates found, for the next one's.
251    diffs: Mutex<DiffCache>,
252}
253
254impl Integrator {
255    pub fn new(ml: Mainline, gate_jobs: usize) -> Integrator {
256        Integrator {
257            ml,
258            gate_jobs: gate_jobs.max(1),
259            board: GateBoard::off(),
260            found: Mutex::new(Vec::new()),
261            held: Mutex::new(BTreeSet::new()),
262            diffs: Mutex::new(DiffCache::default()),
263            rotten_sink: None,
264        }
265    }
266
267    /// The integrator, telling `sink` of rotten rows as soon as it finds
268    /// them.
269    pub fn with_rotten_sink(self, sink: impl Fn(Vec<RottenRow>) + Send + 'static) -> Integrator {
270        Integrator {
271            rotten_sink: Some(Box::new(sink)),
272            ..self
273        }
274    }
275
276    /// Hold the units of `rows` rotten, and pass the rows on: to the sink at
277    /// once, else to [`Integrator::take_rotten`].
278    fn report_rotten(&self, rows: Vec<RottenRow>) {
279        if rows.is_empty() {
280            return;
281        }
282        for r in &rows {
283            self.hold_rotten(&r.unit);
284        }
285        match &self.rotten_sink {
286            Some(sink) => sink(rows),
287            None => self
288                .found
289                .lock()
290                .unwrap_or_else(|e| e.into_inner())
291                .extend(rows),
292        }
293    }
294
295    /// The rows found rotten since the last call, in the order found.
296    pub fn take_rotten(&self) -> Vec<RottenRow> {
297        std::mem::take(&mut *self.found.lock().unwrap_or_else(|e| e.into_inner()))
298    }
299
300    /// Leave `unit`'s rows out of the lane's gates: it is rotten.
301    pub fn hold_rotten(&self, unit: &str) {
302        self.held
303            .lock()
304            .unwrap_or_else(|e| e.into_inner())
305            .insert(unit.to_string());
306    }
307
308    /// Run `unit`'s rows at the lane's gates again: it is no longer held
309    /// rotten (its culprit search found the row flaky, or it was rebuilt).
310    pub fn forget_rotten(&self, unit: &str) {
311        self.held
312            .lock()
313            .unwrap_or_else(|e| e.into_inner())
314            .remove(unit);
315    }
316
317    /// The units held rotten now.
318    fn held_rotten(&self) -> BTreeSet<String> {
319        self.held.lock().unwrap_or_else(|e| e.into_inner()).clone()
320    }
321
322    /// Where this lane runs failing rows on their base.
323    fn base_checkout(&self) -> PristineCheckout {
324        PristineCheckout::new(
325            self.ml.primary.clone(),
326            self.ml.layout.base_checkout(&self.ml.slug),
327        )
328    }
329
330    /// The integrator, reporting its progress to `board`.
331    pub fn with_board(self, board: GateBoard) -> Integrator {
332        Integrator { board, ..self }
333    }
334
335    fn checkout(&self) -> PathBuf {
336        self.ml.checkout()
337    }
338
339    /// Take the lane's integration checkout. `None` = interrupted while
340    /// waiting.
341    fn lock_checkout(&self) -> Result<Option<LaneLock>, CoreError> {
342        self.ml.lock_checkout(&|| {
343            self.board.step("lock");
344            diag(
345                "note: another vitrify process is integrating this SDD — waiting for its integration checkout",
346            );
347        })
348    }
349
350    /// Integrate one Built unit. `before_publish` is a test seam fired after
351    /// the gate and before the CAS/push (lost-race rehearsals).
352    pub fn integrate(
353        &self,
354        req: &IntegrateRequest,
355        memo: &mut GateMemo,
356        before_publish: Option<&dyn Fn()>,
357    ) -> Result<Outcome, CoreError> {
358        let mut out = self.integrate_batch(std::slice::from_ref(req), memo, before_publish)?;
359        Ok(out.pop().unwrap_or(Outcome::LostRace))
360    }
361
362    /// Integrate every request as one batch: one gate run for all of them.
363    /// Outcomes are index-aligned with `reqs`. A red batch of several is
364    /// integrated again one at a time.
365    pub fn integrate_batch(
366        &self,
367        reqs: &[IntegrateRequest],
368        memo: &mut GateMemo,
369        before_publish: Option<&dyn Fn()>,
370    ) -> Result<Vec<Outcome>, CoreError> {
371        let _idle = IdleOnDrop(&self.board);
372        self.board
373            .batch(reqs.iter().map(|r| r.unit.clone()).collect());
374        let mut out: Vec<Option<Outcome>> = vec![None; reqs.len()];
375        match self.lock_checkout()? {
376            Some(_held) => {
377                let all: Vec<usize> = (0..reqs.len()).collect();
378                self.run_batch(&all, reqs, &mut out, memo, before_publish)?;
379            }
380            None => out.fill(Some(Outcome::Interrupted)),
381        }
382        Ok(out
383            .into_iter()
384            .map(|o| o.unwrap_or(Outcome::LostRace))
385            .collect())
386    }
387
388    fn run_batch(
389        &self,
390        idx: &[usize],
391        reqs: &[IntegrateRequest],
392        out: &mut [Option<Outcome>],
393        memo: &mut GateMemo,
394        before_publish: Option<&dyn Fn()>,
395    ) -> Result<(), CoreError> {
396        let mlwt = self.checkout();
397        let ml = self.ml.primary.at(&mlwt);
398        let mut pending: Vec<usize> = idx.to_vec();
399        let units = |which: &[usize]| -> Vec<String> {
400            which.iter().map(|&i| reqs[i].unit.clone()).collect()
401        };
402        let interrupt = |out: &mut [Option<Outcome>], which: &[usize]| {
403            for &i in which {
404                if out[i].is_none() {
405                    out[i] = Some(Outcome::Interrupted);
406                }
407            }
408        };
409
410        for _attempt in 0..3 {
411            if signals::interrupted() {
412                interrupt(out, &pending);
413                return Ok(());
414            }
415            self.board.batch(units(&pending));
416            self.board.step("sync");
417            // 1. sync; record the CAS base. Mainline is first put right
418            // where the audit can do it mechanically, so that a lapsed lease
419            // or a spec change elsewhere is never held against this batch.
420            // A unit of the batch whose own lease has lapsed is decided
421            // before that: skipped (back to the pool), not rejected.
422            self.ml.sync_checkout(&mlwt)?;
423            let at_head = self.ml.sdd_in(&mlwt)?;
424            pending.retain(|&i| {
425                let lapsed = at_head.unit(&reqs[i].unit).is_some_and(|u| {
426                    u.meta.get_int("claim_seq") == reqs[i].token_seq
427                        && u.meta.get_str_or("status", "Draft") == "Claimed"
428                        && !UtcTime::parse(u.meta.get_str_or("claim_expires", ""))
429                            .is_some_and(|e| e > UtcTime::now())
430                });
431                if lapsed {
432                    out[i] = Some(Outcome::SkippedLeaseExpired);
433                }
434                !lapsed
435            });
436            if pending.is_empty() {
437                return Ok(());
438            }
439            match self.ml.heal(true, true) {
440                Ok(_) => {}
441                // mainline too busy to publish the housekeeping: the final
442                // audit decides whether it mattered
443                Err(e) if e.exit_code() == 5 => diag(&format!("note: {e}")),
444                Err(e) => return Err(e),
445            }
446            let base = self.ml.sync_checkout(&mlwt)?;
447
448            // 2–3. fencing, write-set, merge, input check — per unit
449            self.board.batch(units(&pending));
450            self.board.step("merge");
451            let merged = self.assemble(&ml, &mlwt, &base, &pending, reqs, out)?;
452            if merged.is_empty() {
453                return Ok(());
454            }
455            let members: Vec<usize> = merged.iter().map(|m| m.i).collect();
456            self.board.batch(units(&members));
457
458            // 4. the full integration gate, once for the batch
459            let red = |this: &Integrator,
460                       out: &mut [Option<Outcome>],
461                       memo: &mut GateMemo,
462                       command: String,
463                       output: String|
464             -> Result<(), CoreError> {
465                this.ml.pristine(&mlwt, &base)?;
466                if members.len() > 1 {
467                    diag(&format!(
468                        "note: gate red for a batch of {} ({command}); integrating them one at a time",
469                        members.len()
470                    ));
471                    for &i in &members {
472                        this.run_batch(&[i], reqs, out, memo, before_publish)?;
473                    }
474                } else {
475                    out[members[0]] = Some(Outcome::RejectedGate { command, output });
476                }
477                Ok(())
478            };
479            let (rechecked, footprint) = match self.gate(&mlwt, &base, &merged, reqs)? {
480                Gate::Green {
481                    rechecked,
482                    footprint,
483                } => (rechecked, footprint),
484                Gate::Red { command, output } => return red(self, out, memo, command, output),
485                Gate::Interrupted => {
486                    let _ = self.ml.pristine(&mlwt, &base);
487                    interrupt(out, &members);
488                    return Ok(());
489                }
490            };
491            let mut rebuilt = false;
492            let suite = match self.suite(&mlwt, &base, memo, &mut rebuilt)? {
493                Suite::Fine(result) => result,
494                Suite::Regressed { command, output } => {
495                    return red(self, out, memo, command, output);
496                }
497                Suite::Interrupted => {
498                    let _ = self.ml.pristine(&mlwt, &base);
499                    interrupt(out, &members);
500                    return Ok(());
501                }
502            };
503
504            // 5. stamp, journal, ledger, audit, publish
505            match self.finalize(
506                &ml,
507                &mlwt,
508                &base,
509                merged,
510                rebuilt,
511                suite,
512                &rechecked,
513                footprint.as_ref(),
514                reqs,
515                out,
516                memo,
517                before_publish,
518            )? {
519                Final::Published => return Ok(()),
520                Final::Red { command, output } => return red(self, out, memo, command, output),
521                Final::Interrupted => {
522                    let _ = self.ml.pristine(&mlwt, &base);
523                    interrupt(out, &members);
524                    return Ok(());
525                }
526                Final::Redo(remaining) => {
527                    if remaining.is_empty() {
528                        return Ok(());
529                    }
530                    diag(&format!(
531                        "note: {} changed in substance during the gate; integrating again from the new head",
532                        self.ml.branch
533                    ));
534                    pending = remaining;
535                }
536            }
537        }
538        for i in pending {
539            if out[i].is_none() {
540                out[i] = Some(Outcome::LostRace);
541            }
542        }
543        Ok(())
544    }
545
546    /// Fencing check, write-set check, merge and input check for each of
547    /// `which`, on the checkout at `base`. Rejections are recorded in `out`;
548    /// the units that merged are returned in order.
549    fn assemble(
550        &self,
551        ml: &Git,
552        mlwt: &Path,
553        base: &str,
554        which: &[usize],
555        reqs: &[IntegrateRequest],
556        out: &mut [Option<Outcome>],
557    ) -> Result<Vec<Merged>, CoreError> {
558        let inst = self.ml.sdd_in(mlwt)?;
559        let slug = layout::sdd_slug(&inst);
560        let mut candidates: Vec<(usize, String)> = Vec::new();
561        for &i in which {
562            let req = &reqs[i];
563            let branch = layout::unit_branch(&slug, &req.unit, req.token_seq);
564            // fencing check FIRST, against front matter at this head
565            let Some(unit) = inst.unit(&req.unit) else {
566                out[i] = Some(Outcome::RejectedFencing {
567                    reason: format!("unit {} not found at the mainline head", req.unit),
568                });
569                continue;
570            };
571            let current_seq = unit.meta.get_int("claim_seq");
572            if req.token_seq != current_seq {
573                out[i] = Some(Outcome::RejectedFencing {
574                    reason: format!(
575                        "superseded token: branch carries c{}, current claim_seq is {}",
576                        req.token_seq, current_seq
577                    ),
578                });
579                continue;
580            }
581            match unit.meta.get_str_or("status", "Draft") {
582                "Built" => {}
583                "Claimed" => {
584                    let expires = UtcTime::parse(unit.meta.get_str_or("claim_expires", ""));
585                    if !expires.is_some_and(|e| e > UtcTime::now()) {
586                        out[i] = Some(Outcome::SkippedLeaseExpired);
587                        continue;
588                    }
589                }
590                other => {
591                    out[i] = Some(Outcome::RejectedFencing {
592                        reason: format!("unit {} is {other}, not Built/Claimed", req.unit),
593                    });
594                    continue;
595                }
596            }
597            if !ml.branch_exists(&branch).map_err(CoreError::from)? {
598                out[i] = Some(Outcome::RejectedFencing {
599                    reason: format!("work branch {branch} does not exist"),
600                });
601                continue;
602            }
603            // write-set check, before anything merges: every path the branch
604            // changed since it left mainline is owned by the unit (never a
605            // file of the SDD), or a handoff field of its own spec entry
606            let violations = write_set_violations(ml, &inst, unit, mlwt, base, &branch)?;
607            if !violations.is_empty() {
608                out[i] = Some(Outcome::RejectedWriteSet {
609                    paths: violations.iter().map(|v| v.path().to_string()).collect(),
610                    detail: violations
611                        .iter()
612                        .map(|v| v.describe(&req.unit))
613                        .collect::<Vec<_>>()
614                        .join("\n"),
615                });
616                continue;
617            }
618            // input check, still before anything merges: what the branch
619            // says the unit was built from — its Built stamp's trace — must
620            // be what mainline holds now. (It is checked again on the merged
621            // tree; here it also keeps a change to the unit's own entry on
622            // mainline from surfacing as a merge conflict in that file, when
623            // it is simply text the unit has to be rebuilt from.)
624            if let Some(outcome) = stamped_for_current_inputs(ml, &inst, unit, mlwt, &branch)? {
625                out[i] = Some(outcome);
626                continue;
627            }
628            candidates.push((i, branch));
629        }
630
631        let mut merged: Vec<Merged> = Vec::new();
632        for (i, branch) in candidates {
633            let req = &reqs[i];
634            let before = ml.rev_parse("HEAD").map_err(CoreError::from)?;
635            // merge --no-ff; never squash
636            if let Err(e) = ml.merge_no_ff(
637                &branch,
638                &format!("sdd: integrate {} (c{})", req.unit, req.token_seq),
639            ) {
640                // conflict: list conflicted paths, abort, classify
641                let conflicted = ml.conflicted_paths();
642                ml.merge_abort().map_err(CoreError::from)?;
643                ml.reset_hard(&before).map_err(CoreError::from)?;
644                if conflicted.is_empty() {
645                    return Err(e.into());
646                }
647                out[i] = Some(Outcome::OwnershipConflict { paths: conflicted });
648                continue;
649            }
650            // input check: the work must say what it was built from (the
651            // Built stamp's trace), and that must be what mainline holds now
652            let merged_inst = self.ml.sdd_in(mlwt)?;
653            let rejected = match merged_inst.unit(&req.unit) {
654                None => Some(Outcome::RejectedFencing {
655                    reason: format!("unit {} missing after merge", req.unit),
656                }),
657                Some(unit) => built_from_current_inputs(&merged_inst, unit)?,
658            };
659            if let Some(outcome) = rejected {
660                ml.reset_hard(&before).map_err(CoreError::from)?;
661                out[i] = Some(outcome);
662                continue;
663            }
664            merged.push(Merged {
665                i,
666                branch,
667                merge_sha: ml.rev_parse("HEAD").map_err(CoreError::from)?,
668            });
669        }
670        Ok(merged)
671    }
672
673    /// Bootstrap, Build, the Verification tables and Lint, on the merged
674    /// tree; failing rows of units outside the batch are judged on `base`
675    /// (see the module doc).
676    fn gate(
677        &self,
678        mlwt: &Path,
679        base: &str,
680        merged: &[Merged],
681        reqs: &[IntegrateRequest],
682    ) -> Result<Gate, CoreError> {
683        let inst = self.ml.sdd_in(mlwt)?;
684        let cmds = sdd_commands(&model::read_text(&inst.file)?);
685        let verdict = |command: &str, ran: Ran| {
686            if ran.interrupted || signals::interrupted() {
687                Gate::Interrupted
688            } else {
689                Gate::Red {
690                    command: command.to_string(),
691                    output: ran.output,
692                }
693            }
694        };
695        for (step, cmd) in [("bootstrap", &cmds.bootstrap), ("build", &cmds.build)] {
696            let Some(cmd) = cmd else { continue };
697            self.board.step(step);
698            let ran = gate::run_command_watched(cmd, mlwt, &self.board);
699            if !ran.ok() {
700                return Ok(verdict(cmd, ran));
701            }
702        }
703        // the batch's own tables, then the dirty Verified units' — where
704        // semantic conflicts between units surface; each distinct command
705        // runs once. A unit held rotten is not checked again while it fails.
706        let held = self.held_rotten();
707        let slug = unit_graph::slug_of(&inst).to_string();
708        let batch: Vec<String> = merged.iter().map(|m| reqs[m.i].unit.clone()).collect();
709        let mut tables = rows::tables(&inst)?;
710        for t in &mut tables {
711            if held.contains(&t.unit) {
712                t.verified = false;
713            }
714        }
715        let (dirty, snapshot) = self.read_dirty(mlwt, &slug);
716        let selection = rows::for_gate(&tables, &batch, &dirty, cmds.test.as_deref());
717        let footprint = snapshot
718            .and_then(|snap| Footprint::of(&snap, &slug, &selection.units, cmds.test.is_some()));
719        let rows = selection.rows.clone();
720        let own: BTreeSet<String> = tables
721            .iter()
722            .filter(|t| batch.contains(&t.unit))
723            .flat_map(|t| t.rows.iter().cloned())
724            .collect();
725        let verified: BTreeMap<Node, Vec<String>> = tables
726            .iter()
727            .filter(|t| selection.units.contains(&t.unit) && !batch.contains(&t.unit))
728            .map(|t| (Node::new(slug.clone(), t.unit.clone()), t.rows.clone()))
729            .collect();
730        self.board.step("rows");
731        self.board.rows(rows.len());
732        let results = gate::run_rows_watched(&rows, mlwt, self.gate_jobs, false, &self.board);
733        let failed: Vec<(&String, Ran)> = rows
734            .iter()
735            .zip(results)
736            .filter_map(|(cmd, ran)| ran.filter(|r| !r.ok()).map(|r| (cmd, r)))
737            .collect();
738        if let Some((cmd, ran)) = failed.iter().find(|(_, r)| r.interrupted) {
739            return Ok(verdict(cmd, ran.clone()));
740        }
741        // a failing row of the batch's own units is the batch's
742        if let Some((cmd, ran)) = failed.iter().find(|(cmd, _)| own.contains(*cmd)) {
743            return Ok(verdict(cmd, ran.clone()));
744        }
745        if !failed.is_empty() {
746            // the rest: run them on the base, and blame the batch only for
747            // what it broke
748            let commands: Vec<String> = failed.iter().map(|(c, _)| (*c).clone()).collect();
749            let setup: Vec<String> = [&cmds.bootstrap, &cmds.build]
750                .into_iter()
751                .flatten()
752                .cloned()
753                .collect();
754            self.board.step("rows-base");
755            let judged = blame::judge(
756                &commands,
757                &verified,
758                base,
759                &setup,
760                &self.base_checkout(),
761                &ShellRunner,
762            )?;
763            let Judged::Done { verdict: v, .. } = judged else {
764                return Ok(Gate::Interrupted);
765            };
766            if let Some(why) = &v.base_unusable {
767                diag(&format!(
768                    "note: failing rows could not be judged on the base ({why}); the batch is blamed for them"
769                ));
770            }
771            if let Some((cmd, ran)) = failed.iter().find(|(c, _)| v.broken.contains(*c)) {
772                return Ok(verdict(cmd, ran.clone()));
773            }
774            // every failing row fails on the base too: their units are
775            // rotten, and the batch is judged on the rest
776            let mut found: Vec<RottenRow> = Vec::new();
777            for (node, unit_rows) in &v.rotten {
778                let Some(table) = verified.get(node) else {
779                    continue;
780                };
781                for row in unit_rows {
782                    let output = failed
783                        .iter()
784                        .find(|(c, _)| *c == row)
785                        .map(|(_, r)| r.output.clone())
786                        .unwrap_or_default();
787                    found.push(RottenRow {
788                        unit: node.unit.clone(),
789                        row_number: table.iter().position(|c| c == row).map_or(0, |i| i + 1),
790                        row: row.clone(),
791                        base: base.to_string(),
792                        output,
793                    });
794                }
795            }
796            self.report_rotten(found);
797        }
798        if signals::interrupted() {
799            return Ok(Gate::Interrupted);
800        }
801        if let Some(cmd) = &cmds.lint {
802            self.board.step("lint");
803            let ran = gate::run_command_watched(cmd, mlwt, &self.board);
804            if !ran.ok() {
805                return Ok(verdict(cmd, ran));
806            }
807        }
808        let held = self.held_rotten();
809        Ok(Gate::Green {
810            rechecked: selection
811                .units
812                .into_iter()
813                .filter(|u| !batch.contains(u) && !held.contains(u))
814                .collect(),
815            footprint,
816        })
817    }
818
819    /// The Verified units of the SDD `slug` that must be checked again at
820    /// the tree `checkout` holds: a path they are checked against changed
821    /// since their last recorded check. When the repository cannot be read
822    /// as a whole, or its graph has a cycle, every Verified unit is.
823    fn dirty_units(&self, checkout: &Path, slug: &str) -> Vec<String> {
824        self.read_dirty(checkout, slug).0
825    }
826
827    /// [`Integrator::dirty_units`], with the repository as it was read —
828    /// `None` when it could not be read whole.
829    fn read_dirty(&self, checkout: &Path, slug: &str) -> (Vec<String>, Option<Snapshot>) {
830        let git = self.ml.primary.at(checkout);
831        let everything = || match self.ml.sdd_in(checkout) {
832            Ok(inst) => inst
833                .units
834                .iter()
835                .filter(|u| u.meta.get_str_or("status", "Draft") == "Verified")
836                .map(|u| u.unit.clone())
837                .collect(),
838            Err(_) => Vec::new(),
839        };
840        let snapshot = match Snapshot::load_resolvable(&git, checkout, "HEAD") {
841            Ok((snap, _)) => snap,
842            Err(e) => {
843                diag(&format!(
844                    "note: which units a change reaches could not be told ({e}); every Verified unit is checked"
845                ));
846                return (everything(), None);
847            }
848        };
849        let cached = snapshot.dirty_with(
850            &git,
851            Mode::Changes,
852            &mut self.diffs.lock().unwrap_or_else(|e| e.into_inner()),
853        );
854        let units = match cached {
855            Ok(Cascade::Resolved(set)) => set.of_sdd(slug).map(|d| d.node.unit.clone()).collect(),
856            Ok(Cascade::Cycles(_)) => everything(),
857            Err(e) => {
858                diag(&format!(
859                    "note: which units a change reaches could not be told ({e}); every Verified unit is checked"
860                ));
861                everything()
862            }
863        };
864        (units, Some(snapshot))
865    }
866
867    /// The §5 Test command on the merged tree: the whole suite, which
868    /// Verification rows — each selecting a few tests — cannot stand in for.
869    /// It gates as a regression check: a merge must not turn it from passing
870    /// to failing. While it already fails at the head (no tests yet, tests
871    /// awaiting their code, an earlier breakage) no merge is judged by it.
872    /// Its state before the merges is taken from `memo`, or measured at
873    /// `base` — which resets the checkout (`rebuilt`).
874    fn suite(
875        &self,
876        mlwt: &Path,
877        base: &str,
878        memo: &mut GateMemo,
879        rebuilt: &mut bool,
880    ) -> Result<Suite, CoreError> {
881        let inst = self.ml.sdd_in(mlwt)?;
882        let cmds = sdd_commands(&model::read_text(&inst.file)?);
883        let Some(test) = cmds.test.clone() else {
884            return Ok(Suite::Fine(None));
885        };
886        self.board.step("test");
887        let after = gate::run_command_watched(&test, mlwt, &self.board);
888        if after.interrupted || signals::interrupted() {
889            return Ok(Suite::Interrupted);
890        }
891        if after.ok() {
892            return Ok(Suite::Fine(Some(true)));
893        }
894        let before = match self.suite_known(memo, base)? {
895            Some(passed) => passed,
896            None => {
897                // measure at the base: the tree as it was before the merges
898                self.board.step("test-base");
899                self.ml.pristine(mlwt, base)?;
900                *rebuilt = true;
901                let mut passed = true;
902                for cmd in [&cmds.bootstrap, &cmds.build, &Some(test.clone())]
903                    .into_iter()
904                    .flatten()
905                {
906                    let ran = gate::run_command_watched(cmd, mlwt, &self.board);
907                    if ran.interrupted || signals::interrupted() {
908                        return Ok(Suite::Interrupted);
909                    }
910                    if !ran.ok() {
911                        passed = false;
912                        break;
913                    }
914                }
915                memo.suite = Some((base.to_string(), passed));
916                passed
917            }
918        };
919        if before {
920            Ok(Suite::Regressed {
921                command: test,
922                output: format!(
923                    "{}\n(the §5 Test command passed before this merge and fails after it)",
924                    after.output
925                ),
926            })
927        } else {
928            diag(&format!(
929                "note: the §5 Test command already fails at the {} head — integrations are not judged by it until it passes: {test}",
930                self.ml.branch
931            ));
932            Ok(Suite::Fine(Some(false)))
933        }
934    }
935
936    /// The Test command's result at `commit`, if `memo` holds one that
937    /// still applies.
938    fn suite_known(&self, memo: &GateMemo, commit: &str) -> Result<Option<bool>, CoreError> {
939        match &memo.suite {
940            Some((at, passed)) if benign(&self.ml, at, commit)? => Ok(Some(*passed)),
941            _ => Ok(None),
942        }
943    }
944
945    /// Steps 5–6: on the gated tree, stamp every unit Verified, append the
946    /// journal events, regenerate the ledger, require a clean audit, commit
947    /// and publish. If mainline moved since the gate started, the gate's
948    /// verdict still stands when the commits in between moved nothing but
949    /// protocol state (claims, renewals, releases, recorded questions): the
950    /// merges are then replayed on the new head and published from there.
951    #[allow(clippy::too_many_arguments)]
952    fn finalize(
953        &self,
954        ml: &Git,
955        mlwt: &Path,
956        gated_base: &str,
957        mut merged: Vec<Merged>,
958        mut rebuild: bool,
959        suite: Option<bool>,
960        rechecked: &[String],
961        footprint: Option<&Footprint>,
962        reqs: &[IntegrateRequest],
963        out: &mut [Option<Outcome>],
964        memo: &mut GateMemo,
965        before_publish: Option<&dyn Fn()>,
966    ) -> Result<Final, CoreError> {
967        let mut base = gated_base.to_string();
968        let mut heals_left = 2;
969        // The merges, stamps and audit are made in the lane's own checkout,
970        // with no other writer waiting on them; only the move of mainline
971        // itself takes this process's mainline turn. A publish that loses
972        // the race to another lane's replays them on the new head — while
973        // the commits in between leave the gate's verdict standing.
974        for _ in 0..PUBLISH_TRIES {
975            self.board.step("publish");
976            if signals::interrupted() {
977                return Ok(Final::Interrupted);
978            }
979            let head = self.ml.head()?;
980            if head != base {
981                // protocol state alone, or changes the gate never looked
982                // at: the verdict stands, and the merges are replayed
983                let untouched = self.benign(gated_base, &head)?
984                    || footprint.is_some_and(|f| f.untouched(&self.ml.primary, gated_base, &head));
985                if !untouched {
986                    return Ok(Final::Redo(merged.iter().map(|m| m.i).collect()));
987                }
988                rebuild = true;
989            }
990            if rebuild {
991                self.ml.pristine(mlwt, &head)?;
992                let before: Vec<usize> = merged.iter().map(|m| m.i).collect();
993                merged = self.assemble(ml, mlwt, &head, &before, reqs, out)?;
994                if merged.len() != before.len() {
995                    // a member dropped out: the gated tree is not this tree
996                    self.ml.pristine(mlwt, &head)?;
997                    return Ok(Final::Redo(merged.iter().map(|m| m.i).collect()));
998                }
999                base = head.clone();
1000            }
1001            // What is stamped, audited and published is the merged tree and
1002            // nothing else. Whatever the gate's commands left in the
1003            // checkout — files they wrote, tracked files they rewrote — goes
1004            // here, so the result never depends on whether the merges had
1005            // to be replayed.
1006            ml.reset_hard("HEAD").map_err(CoreError::from)?;
1007            ml.clean_fdq().map_err(CoreError::from)?;
1008
1009            let inst = self.ml.sdd_in(mlwt)?;
1010            for m in &merged {
1011                let req = &reqs[m.i];
1012                let Some(unit) = inst.unit(&req.unit) else {
1013                    continue;
1014                };
1015                stamp_verified(&inst, unit, short(&m.merge_sha))?;
1016                let branch_sha = ml.rev_parse(&m.branch).map_err(CoreError::from)?;
1017                for (event, actor, commit) in [
1018                    ("built", &req.builder_holder, short(&branch_sha)),
1019                    ("verified", &req.integrator_id, short(&m.merge_sha)),
1020                ] {
1021                    append_event(
1022                        &inst,
1023                        Event {
1024                            event: event.to_string(),
1025                            unit: Some(req.unit.clone()),
1026                            actor: Some(actor.clone()),
1027                            claim_seq: Some(req.token_seq),
1028                            commit: Some(commit.to_string()),
1029                            ..Default::default()
1030                        },
1031                    )?;
1032                }
1033            }
1034            // the re-checks the gate made, on the tree it gated
1035            let gated = short(&ml.rev_parse("HEAD").map_err(CoreError::from)?).to_string();
1036            let held = self.held_rotten();
1037            let stamp = model::render_stamp(
1038                &UtcTime::now().format_date(),
1039                inst.meta.get_str_or("version", "0.0.0"),
1040                &gated,
1041            );
1042            for uid in rechecked.iter().filter(|u| !held.contains(*u)) {
1043                let Some(unit) = inst.unit(uid) else {
1044                    continue;
1045                };
1046                if unit.meta.get_str_or("status", "Draft") != "Verified" {
1047                    continue;
1048                }
1049                model::rewrite_unit_meta(&inst.handle(), unit, |inner| {
1050                    yamlish::set_scalar_in_place(inner, "verified", &stamp)
1051                })?;
1052                append_event(
1053                    &inst,
1054                    Event {
1055                        event: "verified".to_string(),
1056                        unit: Some(uid.clone()),
1057                        actor: Some(journal::RECHECK_ACTOR.to_string()),
1058                        commit: Some(gated.clone()),
1059                        ..Default::default()
1060                    },
1061                )?;
1062            }
1063            let stamped = self.ml.sdd_in(mlwt)?;
1064            ledger::regen(&stamped, &UtcTime::now().format_date())?;
1065            // audit --skip-rotten --journal: must be clean, run last on the
1066            // stamped tree (checks 1–3 on what the merges brought in; 5–7 on
1067            // the state about to be published)
1068            let (findings, _) = audit::run(
1069                &stamped,
1070                mlwt,
1071                &cmd::audit_options(
1072                    audit::Options {
1073                        skip_rotten: true,
1074                        ..Default::default()
1075                    },
1076                    mlwt,
1077                    &stamped,
1078                ),
1079                &ShRunner,
1080                UtcTime::now(),
1081            )?;
1082            // A lease this run does not hold that lapsed since the sync, or
1083            // a trace elsewhere that a change on mainline staled: mainline's
1084            // own state, and mechanically put right — not a verdict on this
1085            // batch. Put it right and publish from the new head.
1086            let batch: Vec<&str> = merged.iter().map(|m| reqs[m.i].unit.as_str()).collect();
1087            let elsewhere = |f: &audit::Finding| {
1088                matches!(f.check, 5 | 7) && !batch.contains(&f.subject.as_str())
1089            };
1090            if !findings.is_empty() && findings.iter().all(elsewhere) {
1091                if heals_left == 0 {
1092                    self.ml.pristine(mlwt, &base)?;
1093                    return Ok(Final::Redo(merged.iter().map(|m| m.i).collect()));
1094                }
1095                heals_left -= 1;
1096                match self.ml.heal(true, true) {
1097                    Ok(_) => {}
1098                    Err(e) if e.exit_code() == 5 => diag(&format!("note: {e}")),
1099                    Err(e) => return Err(e),
1100                }
1101                rebuild = true;
1102                continue;
1103            }
1104            if !findings.is_empty() {
1105                self.ml.pristine(mlwt, &base)?;
1106                return Ok(Final::Red {
1107                    command: "vitrify audit --skip-rotten --journal".to_string(),
1108                    output: findings
1109                        .iter()
1110                        .map(|f| format!("[check {}] {}: {}", f.check, f.subject, f.cause))
1111                        .collect::<Vec<_>>()
1112                        .join("\n"),
1113                });
1114            }
1115            append_event(
1116                &stamped,
1117                Event {
1118                    event: "audit".to_string(),
1119                    actor: Some("audit".to_string()),
1120                    findings: Some(0),
1121                    // the suite passed on the gated tree: its new anchor
1122                    suite: (suite == Some(true)).then(|| journal::SUITE_PASS.to_string()),
1123                    commit: Some(gated.clone()),
1124                    ..Default::default()
1125                },
1126            )?;
1127            ml.add_all().map_err(CoreError::from)?;
1128            let label = merged
1129                .iter()
1130                .map(|m| format!("{} (c{})", reqs[m.i].unit, reqs[m.i].token_seq))
1131                .collect::<Vec<_>>()
1132                .join(", ");
1133            ml.commit(&format!("sdd: verify {label}"))
1134                .map_err(CoreError::from)?;
1135            let verify_sha = ml.rev_parse("HEAD").map_err(CoreError::from)?;
1136
1137            if let Some(hook) = before_publish {
1138                hook();
1139            }
1140            if signals::interrupted() {
1141                return Ok(Final::Interrupted);
1142            }
1143
1144            // publish every merge and the verify commit as one move; the
1145            // primary checkout follows in the same turn
1146            let turn = claim::tx_lock();
1147            if let Some(landed) = self.ml.publish(&verify_sha, &base)? {
1148                self.ml.follow(&landed)?;
1149                drop(turn);
1150                if let Some(passed) = suite {
1151                    memo.suite = Some((verify_sha.clone(), passed));
1152                }
1153                let slug = layout::sdd_slug(&stamped);
1154                for m in &merged {
1155                    let req = &reqs[m.i];
1156                    // the merged attempt's worktree and branch are done
1157                    let wt = self
1158                        .ml
1159                        .layout
1160                        .unit_worktree(&slug, &req.unit, req.token_seq);
1161                    if wt.exists() {
1162                        let _ = self.ml.primary.worktree_remove(&wt);
1163                    }
1164                    self.ml
1165                        .primary
1166                        .delete_branch(&m.branch)
1167                        .map_err(CoreError::from)?;
1168                    out[m.i] = Some(Outcome::Verified {
1169                        merge_commit: m.merge_sha.clone(),
1170                        verify_commit: verify_sha.clone(),
1171                    });
1172                }
1173                return Ok(Final::Published);
1174            }
1175            drop(turn);
1176            diag(&format!(
1177                "note: lost publish race integrating {label} on {}; redoing from sync",
1178                self.ml.branch
1179            ));
1180            rebuild = true;
1181        }
1182        Ok(Final::Redo(merged.iter().map(|m| m.i).collect()))
1183    }
1184
1185    /// [`benign`] for this integrator's repository.
1186    pub fn benign(&self, old: &str, new: &str) -> Result<bool, CoreError> {
1187        benign(&self.ml, old, new)
1188    }
1189
1190    /// A re-check batch for `units`, which a change reached and whose
1191    /// dependencies have no work pending: in the lane's integration checkout
1192    /// at the mainline head (taken under its lock), their rows then the §5
1193    /// Test command ([`recheck::run`]). The passes are recorded as one
1194    /// re-check commit; failing rows make their units rotten, held out of
1195    /// the lane's later gates. No worker takes part.
1196    pub fn recheck(&self, units: &[String]) -> Result<Rechecked, CoreError> {
1197        let mlwt = self.checkout();
1198        let _idle = IdleOnDrop(&self.board);
1199        self.board.batch(units.to_vec());
1200        let mut out = Rechecked::default();
1201        let Some(_held) = self.lock_checkout()? else {
1202            out.interrupted = true;
1203            return Ok(out);
1204        };
1205        self.board.step("recheck");
1206        let head = self.ml.sync_checkout(&mlwt)?;
1207        let report = recheck::run(
1208            &self.ml.primary.at(&mlwt),
1209            &head,
1210            &self.ml.sdd_rel,
1211            units,
1212            &PoolRunner(self.gate_jobs),
1213        )?;
1214        out.commit = report.commit.clone();
1215        if report.interrupted || signals::interrupted() {
1216            out.interrupted = true;
1217            return Ok(out);
1218        }
1219        if let Some(b) = &report.broken {
1220            out.broken = Some((b.command.clone(), b.output.clone()));
1221            return Ok(out);
1222        }
1223        out.suite_ran = report.suite.is_some();
1224        let inst = self.ml.sdd_in(&mlwt)?;
1225        // the verdict goes out before the passes are published
1226        self.report_rotten(rotten_of(&inst, &report)?);
1227        out.rotten = self.take_rotten();
1228        let edits = report.edits();
1229        out.passed = edits.verified.clone();
1230        out.recorded = record_recheck(&self.ml, &edits);
1231        Ok(out)
1232    }
1233
1234    /// The mainline head as the termination report needs it: the audit
1235    /// (checks 1–3 and 5–7), the rows of the units a change reached since
1236    /// their last recorded check, and — when `want_suite` — the §5 Test
1237    /// command, unless its recorded pass still holds. Units held rotten are
1238    /// not run again.
1239    pub fn check_head(
1240        &self,
1241        memo: &mut GateMemo,
1242        want_suite: bool,
1243    ) -> Result<HeadCheck, CoreError> {
1244        let mlwt = self.checkout();
1245        let _idle = IdleOnDrop(&self.board);
1246        self.board.batch(Vec::new());
1247        let Some(_held) = self.lock_checkout()? else {
1248            return Ok(HeadCheck {
1249                head: String::new(),
1250                findings: Vec::new(),
1251                broken: None,
1252                suite: None,
1253                interrupted: true,
1254            });
1255        };
1256        self.board.step("head-check");
1257        let head = self.ml.sync_checkout(&mlwt)?;
1258        let inst = self.ml.sdd_in(&mlwt)?;
1259        let cmds = sdd_commands(&model::read_text(&inst.file)?);
1260        let mut check = HeadCheck {
1261            head: head.clone(),
1262            findings: Vec::new(),
1263            broken: None,
1264            suite: None,
1265            interrupted: false,
1266        };
1267        let slug = unit_graph::slug_of(&inst).to_string();
1268        let held = self.held_rotten();
1269        let dirty: Vec<String> = self
1270            .dirty_units(&mlwt, &slug)
1271            .into_iter()
1272            .filter(|u| !held.contains(u))
1273            .collect();
1274        let tables = rows::tables(&inst)?;
1275        let selection = rows::for_preflight(&tables, &dirty);
1276        let suite_known = match self.suite_known(memo, &head)? {
1277            Some(passed) => Some(passed),
1278            None => self.suite_recorded(&mlwt, &slug).then_some(true),
1279        };
1280        let run_suite = want_suite && cmds.test.is_some() && suite_known.is_none();
1281        // commands are about to run here: the environment first
1282        if !selection.rows.is_empty() || run_suite {
1283            for cmd in [&cmds.bootstrap, &cmds.build].into_iter().flatten() {
1284                let ran = gate::run_command_watched(cmd, &mlwt, &self.board);
1285                if ran.interrupted || signals::interrupted() {
1286                    check.interrupted = true;
1287                    return Ok(check);
1288                }
1289                if !ran.ok() {
1290                    check.broken = Some((cmd.clone(), ran.output));
1291                    return Ok(check);
1292                }
1293            }
1294        }
1295        let (mut findings, _) = audit::run(
1296            &inst,
1297            &mlwt,
1298            &cmd::audit_options(
1299                audit::Options {
1300                    skip_rotten: true,
1301                    ..Default::default()
1302                },
1303                &mlwt,
1304                &inst,
1305            ),
1306            &ShRunner,
1307            UtcTime::now(),
1308        )?;
1309        if !selection.rows.is_empty() {
1310            self.board.step("rows");
1311            self.board.rows(selection.rows.len());
1312            let results =
1313                gate::run_rows_watched(&selection.rows, &mlwt, self.gate_jobs, false, &self.board);
1314            if signals::interrupted() {
1315                check.interrupted = true;
1316                return Ok(check);
1317            }
1318            for t in tables.iter().filter(|t| selection.units.contains(&t.unit)) {
1319                for (row, ran) in selection.rows.iter().zip(&results) {
1320                    if t.rows.contains(row)
1321                        && let Some(ran) = ran
1322                        && !ran.ok()
1323                    {
1324                        findings.push(audit::Finding {
1325                            check: 4,
1326                            subject: t.unit.clone(),
1327                            cause: format!("Verification row fails: `{row}` (exit {})", ran.code),
1328                            remediation: format!(
1329                                "run `{row}` in a checkout of the head and fix what it reports"
1330                            ),
1331                        });
1332                    }
1333                }
1334            }
1335        }
1336        check.findings = findings;
1337
1338        if want_suite && let Some(test) = &cmds.test {
1339            check.suite = Some(match suite_known {
1340                Some(passed) => (test.clone(), passed, String::new()),
1341                None => {
1342                    self.board.step("test");
1343                    let ran = gate::run_command_watched(test, &mlwt, &self.board);
1344                    if ran.interrupted || signals::interrupted() {
1345                        check.interrupted = true;
1346                        return Ok(check);
1347                    }
1348                    memo.suite = Some((head.clone(), ran.ok()));
1349                    (test.clone(), ran.ok(), ran.output)
1350                }
1351            });
1352        }
1353        Ok(check)
1354    }
1355
1356    /// Whether the SDD `slug`'s journal records a §5 Test pass that still
1357    /// holds at the tree `checkout` holds.
1358    fn suite_recorded(&self, checkout: &Path, slug: &str) -> bool {
1359        let git = self.ml.primary.at(checkout);
1360        match Snapshot::load_resolvable(&git, checkout, "HEAD").and_then(|(s, _)| {
1361            s.dirty_with(
1362                &git,
1363                Mode::Changes,
1364                &mut self.diffs.lock().unwrap_or_else(|e| e.into_inner()),
1365            )
1366        }) {
1367            Ok(Cascade::Resolved(set)) => set
1368                .suite(slug)
1369                .is_some_and(|s| s.anchor.is_some() && s.dirty.is_none()),
1370            _ => false,
1371        }
1372    }
1373}
1374
1375/// What a gate checked or read, beyond protocol state: the units whose
1376/// rows ran and everything they depend on, the SDD's unmanaged files, the
1377/// paths outside every scope it takes as input, and — when it ran the §5
1378/// Test command — the SDD's whole scope. A test path (§6 `tests:`) counts
1379/// only for a gate of its own SDD: a generated test when its owner is
1380/// checked or the suite ran, a pre-existing test always; another SDD's test
1381/// paths are never read. A commit that changed nothing of it cannot change
1382/// the gate's verdict.
1383#[derive(Debug, Clone)]
1384pub struct Footprint {
1385    /// The gated SDD's slug.
1386    slug: String,
1387    /// The units whose rows ran, and every unit they depend on, in any SDD.
1388    checked: BTreeSet<Node>,
1389    /// The §5 Test command ran: every file in the SDD's scope was read.
1390    suite: bool,
1391    ownership: Ownership,
1392    spec: SpecFiles,
1393}
1394
1395impl Footprint {
1396    /// The footprint of a gate over `units` (the units whose rows ran) of
1397    /// the SDD `slug`, read from `snap`. `None` when the graph has no
1398    /// closures to give (a cycle).
1399    fn of(snap: &Snapshot, slug: &str, units: &[String], suite: bool) -> Option<Footprint> {
1400        let resolution = snap.resolved.as_ref().ok()?;
1401        let mut checked: BTreeSet<Node> = BTreeSet::new();
1402        for unit in units {
1403            let node = Node::new(slug, unit.as_str());
1404            checked.extend(resolution.closure(&node).into_iter().cloned());
1405            checked.insert(node);
1406        }
1407        Some(Footprint {
1408            slug: slug.to_string(),
1409            checked,
1410            suite,
1411            ownership: snap.ownership.clone(),
1412            spec: snap.spec.clone(),
1413        })
1414    }
1415
1416    /// Whether `path` is something the gate checked or read.
1417    fn reads(&self, path: &str) -> bool {
1418        match self.ownership.classify(path) {
1419            Owner::Spec(s) => s == self.slug,
1420            Owner::Unit(n) => self.checked.contains(&n) || (self.suite && n.slug == self.slug),
1421            Owner::Test {
1422                slug: s,
1423                unit: Some(n),
1424            } => s == self.slug && (self.checked.contains(&n) || self.suite),
1425            Owner::Test {
1426                slug: s,
1427                unit: None,
1428            } => s == self.slug,
1429            Owner::Unmanaged(s) => s == self.slug,
1430            Owner::Outside => self.ownership.takes_outside(&self.slug, path),
1431        }
1432    }
1433
1434    /// Whether `old..new` changed, beyond protocol state, nothing the gate
1435    /// checked or read (`new` descending from `old`).
1436    pub fn untouched(&self, git: &Git, old: &str, new: &str) -> bool {
1437        if old == new {
1438            return true;
1439        }
1440        if !git.is_ancestor(old, new).unwrap_or(false) {
1441            return false;
1442        }
1443        match dirty::substantive_changes(git, old, new, &self.spec) {
1444            Ok(paths) => !paths.iter().any(|p| self.reads(p)),
1445            Err(_) => false,
1446        }
1447    }
1448}
1449
1450/// What a lane's re-check batch found.
1451#[derive(Debug, Clone, Default)]
1452pub struct Rechecked {
1453    /// The commit checked.
1454    pub commit: String,
1455    /// The units whose rows all passed.
1456    pub passed: Vec<String>,
1457    /// Their passes reached mainline as a re-check commit.
1458    pub recorded: bool,
1459    /// Rows that failed: their units are rotten.
1460    pub rotten: Vec<RottenRow>,
1461    /// A §5 Bootstrap or Build that failed, so no row ran: (command, output).
1462    pub broken: Option<(String, String)>,
1463    /// The §5 Test command ran.
1464    pub suite_ran: bool,
1465    pub interrupted: bool,
1466}
1467
1468/// Runs a re-check's commands through the gate pool, its rows side by side.
1469pub(crate) struct PoolRunner(pub usize);
1470
1471impl recheck::Runner for PoolRunner {
1472    fn run(&self, cmd: &str, cwd: &Path) -> recheck::CommandResult {
1473        recheck::ShRunner.run(cmd, cwd)
1474    }
1475
1476    fn run_rows(&self, rows: &[String], cwd: &Path) -> Vec<recheck::CommandResult> {
1477        gate::run_rows(rows, cwd, self.0, false)
1478            .into_iter()
1479            .map(|ran| match ran {
1480                Some(ran) => recheck::CommandResult {
1481                    passed: ran.ok(),
1482                    interrupted: ran.interrupted,
1483                    output: ran.output,
1484                },
1485                None => recheck::CommandResult {
1486                    passed: false,
1487                    interrupted: true,
1488                    output: String::new(),
1489                },
1490            })
1491            .collect()
1492    }
1493}
1494
1495/// The rows a re-check found failing, as rotten rows at the commit it
1496/// checked: nothing in a batch broke them, so something already on
1497/// mainline did — or they are flaky, which culprit finding sorts out.
1498pub(crate) fn rotten_of(
1499    inst: &Instance,
1500    report: &recheck::Report,
1501) -> Result<Vec<RottenRow>, CoreError> {
1502    let tables = rows::tables(inst)?;
1503    let mut out = Vec::new();
1504    for u in report.units.iter().filter(|u| !u.passed) {
1505        let table = tables
1506            .iter()
1507            .find(|t| t.unit == u.unit)
1508            .map(|t| t.rows.as_slice())
1509            .unwrap_or_default();
1510        for f in &u.failures {
1511            out.push(RottenRow {
1512                unit: u.unit.clone(),
1513                row_number: table
1514                    .iter()
1515                    .position(|r| r == &f.command)
1516                    .map_or(0, |i| i + 1),
1517                row: f.command.clone(),
1518                base: report.commit.clone(),
1519                output: f.output.clone(),
1520            });
1521        }
1522    }
1523    Ok(out)
1524}
1525
1526/// Record a re-check's passes on mainline as one commit — fresh stamps,
1527/// `verified` events by `recheck`, `suite: "pass"` — published like any
1528/// other. `false` when there was nothing to record or it could not be.
1529pub(crate) fn record_recheck(ml: &Mainline, edits: &recheck::Edits) -> bool {
1530    if edits.is_empty() {
1531        return false;
1532    }
1533    let message = if edits.verified.is_empty() {
1534        format!("sdd: re-check the suite at {}", edits.commit)
1535    } else {
1536        format!(
1537            "sdd: re-check {} at {}",
1538            edits.verified.join(", "),
1539            edits.commit
1540        )
1541    };
1542    let published = ml.publish_tx(&message, &|tx| {
1543        let inst = ml.sdd_in(tx)?;
1544        let findings = recheck::apply(&inst, tx, edits)?;
1545        if !findings.is_empty() {
1546            diag(&format!(
1547                "note: the re-check was not recorded — the audit found {} finding(s) after it",
1548                findings.len()
1549            ));
1550            return Ok(false);
1551        }
1552        Ok(true)
1553    });
1554    match published {
1555        Ok(commit) => commit.is_some(),
1556        Err(e) => {
1557            // the checks still passed; only their record is missing
1558            diag(&format!("note: the re-check was not recorded: {e}"));
1559            false
1560        }
1561    }
1562}
1563
1564/// Where the repository's SDDs keep their files, read from the primary
1565/// checkout: what tells protocol state from everything else. The lane's own
1566/// SDD is always among them, whatever its file is called.
1567fn spec_files(ml: &Mainline) -> SpecFiles {
1568    let (mut sdds, _) = cmd::loaded(&ml.primary.dir, None);
1569    if let Ok(own) = ml.sdd_in(&ml.primary.dir) {
1570        sdds.push(own);
1571    }
1572    SpecFiles::of(&ml.primary.dir, &sdds)
1573}
1574
1575/// Whether `old..new` moved nothing but protocol state — journals,
1576/// ledgers, decision and change logs, the vitrify-managed fields of unit
1577/// entries, in any SDD of the repository. Such commits — claims, renewals,
1578/// releases, recorded questions — change nothing a build, a test or a lint
1579/// reads, so what a gate established at `old` holds at `new`.
1580pub fn benign(ml: &Mainline, old: &str, new: &str) -> Result<bool, CoreError> {
1581    if old == new {
1582        return Ok(true);
1583    }
1584    Ok(substantive(ml, old, new)?.is_some_and(|paths| paths.is_empty()))
1585}
1586
1587/// The paths `old..new` changed beyond protocol state
1588/// ([`dirty::substantive_changes`]), `None` when `new` does not descend
1589/// from `old`; remembered: every lane asks the same of each new head, and
1590/// the answer is the same for all of them.
1591fn substantive(ml: &Mainline, old: &str, new: &str) -> Result<Option<Vec<String>>, CoreError> {
1592    type Memo = Vec<((String, String), Option<Vec<String>>)>;
1593    static SEEN: std::sync::Mutex<Memo> = std::sync::Mutex::new(Vec::new());
1594    let key = (old.to_string(), new.to_string());
1595    if let Some((_, paths)) = SEEN
1596        .lock()
1597        .unwrap_or_else(|e| e.into_inner())
1598        .iter()
1599        .find(|(k, _)| *k == key)
1600    {
1601        return Ok(paths.clone());
1602    }
1603    let paths = if ml.primary.is_ancestor(old, new).map_err(CoreError::from)? {
1604        Some(dirty::substantive_changes(
1605            &ml.primary,
1606            old,
1607            new,
1608            &spec_files(ml),
1609        )?)
1610    } else {
1611        None
1612    };
1613    let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner());
1614    seen.push((key, paths.clone()));
1615    if seen.len() > 64 {
1616        seen.remove(0);
1617    }
1618    Ok(paths)
1619}
1620
1621/// Whether `old..new` changed the SDD's own text — anything under its root
1622/// beyond protocol state. Only then can a recorded trace have gone stale.
1623pub fn spec_moved(ml: &Mainline, old: &str, new: &str) -> Result<bool, CoreError> {
1624    if old == new {
1625        return Ok(false);
1626    }
1627    let root = cmd::sdd_arg(&ml.sdd_rel);
1628    let under = |p: &str| root == "." || p == root || p.starts_with(&format!("{root}/"));
1629    Ok(match substantive(ml, old, new)? {
1630        Some(paths) => paths.iter().any(|p| under(p)),
1631        None => true,
1632    })
1633}
1634
1635fn short(sha: &str) -> &str {
1636    &sha[..7.min(sha.len())]
1637}
1638
1639/// A unit's front matter as `text` — its unit file, or the single-file SDD
1640/// holding its region — has it.
1641fn unit_meta_in(shape: Shape, text: &str, uid: &str) -> Option<model::Meta> {
1642    match shape {
1643        Shape::Bundle => model::front_matter(text),
1644        Shape::Single => {
1645            let (start, end) = model::find_unit_span(text, uid)?;
1646            let region = &text[start..end];
1647            let (_, _, inner_start, inner_end) = model::find_meta_block_span(region)?;
1648            Some(model::Meta(yamlish::parse(&region[inner_start..inner_end])))
1649        }
1650    }
1651}
1652
1653/// The input check before the merge: `None` when the unit's entry on
1654/// `branch` is stamped Built with a trace equal to what its inputs hash to
1655/// at the head (`inst`, loaded from the checkout at `root`). The write-set
1656/// check has passed, so the branch changed nothing of that entry but the
1657/// handoff fields.
1658fn stamped_for_current_inputs(
1659    ml: &Git,
1660    inst: &Instance,
1661    unit: &model::Unit,
1662    root: &Path,
1663    branch: &str,
1664) -> Result<Option<Outcome>, CoreError> {
1665    let spec_file = WriteSet::of(inst, unit, root)?.spec_file;
1666    let stamped = ml
1667        .show_text(branch, &spec_file)
1668        .map_err(CoreError::from)?
1669        .and_then(|text| unit_meta_in(inst.shape, &text, &unit.unit))
1670        .unwrap_or_default();
1671    judge_stamp(inst, unit, &stamped)
1672}
1673
1674/// The input check: `None` when the merged unit is stamped Built with a
1675/// trace equal to what its inputs hash to now.
1676fn built_from_current_inputs(
1677    merged: &Instance,
1678    unit: &model::Unit,
1679) -> Result<Option<Outcome>, CoreError> {
1680    judge_stamp(merged, unit, &unit.meta)
1681}
1682
1683/// `stamped` (a version of `unit`'s front matter) against the unit's inputs
1684/// as `inst` holds them.
1685fn judge_stamp(
1686    inst: &Instance,
1687    unit: &model::Unit,
1688    stamped: &model::Meta,
1689) -> Result<Option<Outcome>, CoreError> {
1690    let merged = inst;
1691    let status = stamped.get_str_or("status", "Draft");
1692    let recorded = stamped.get_map("trace").cloned().unwrap_or_default();
1693    if status != "Built" || recorded.is_empty() {
1694        return Ok(Some(Outcome::RejectedNotBuilt {
1695            reason: format!(
1696                "the work does not stamp {} Built (status {status}{}) — `vitrify trace record --stamp built` is the handoff",
1697                unit.unit,
1698                if recorded.is_empty() {
1699                    ", no trace"
1700                } else {
1701                    ""
1702                }
1703            ),
1704        }));
1705    }
1706    let (current, problems) = trace::compute(merged, unit)?;
1707    if !problems.is_empty() {
1708        // its reading set no longer resolves (a consumed contract gone, a
1709        // pin's authority moved): the work was built from what is no more,
1710        // a verdict on this unit alone
1711        return Ok(Some(Outcome::RejectedStaleInputs {
1712            keys: problems.iter().map(|p| p.to_string()).collect(),
1713        }));
1714    }
1715    let mismatches = trace::verify(&recorded, &current);
1716    if mismatches.is_empty() {
1717        Ok(None)
1718    } else {
1719        Ok(Some(Outcome::RejectedStaleInputs {
1720            keys: mismatches.into_iter().map(|m| m.key).collect(),
1721        }))
1722    }
1723}
1724
1725/// The write-set check (schema §13.3): classify every path the branch changed
1726/// since it forked from `base` against the unit's write-set as defined at
1727/// `base`. Empty = the work stays inside what the unit may write.
1728fn write_set_violations(
1729    ml: &Git,
1730    inst: &Instance,
1731    unit: &model::Unit,
1732    root: &Path,
1733    base: &str,
1734    branch: &str,
1735) -> Result<Vec<Violation>, CoreError> {
1736    let ws = WriteSet::of(inst, unit, root)?;
1737    let fork = ml.merge_base(base, branch).map_err(CoreError::from)?;
1738    let changed = ml.changed_paths(&fork, branch).map_err(CoreError::from)?;
1739    let spec_file = ws.spec_file.clone();
1740    let versions = || {
1741        (
1742            ml.show_text(&fork, &spec_file).ok().flatten(),
1743            ml.show_text(branch, &spec_file).ok().flatten(),
1744        )
1745    };
1746    Ok(ws.violations(&changed, versions))
1747}
1748
1749/// `trace record --stamp verified --commit <sha>` via core (one hashing
1750/// implementation; this is wiring, not a second recipe).
1751fn stamp_verified(inst: &Instance, unit: &model::Unit, commit: &str) -> Result<(), CoreError> {
1752    let (trace_map, problems) = trace::compute(inst, unit)?;
1753    if !problems.is_empty() {
1754        return Err(CoreError::refusal(
1755            4,
1756            problems
1757                .iter()
1758                .map(|p| format!("error: {p}"))
1759                .collect::<Vec<_>>()
1760                .join("\n"),
1761        ));
1762    }
1763    let stamp = model::render_stamp(
1764        &UtcTime::now().format_date(),
1765        inst.meta.get_str_or("version", "0.0.0"),
1766        commit,
1767    );
1768    model::rewrite_unit_meta(&inst.handle(), unit, |inner| {
1769        let b = yamlish::set_scalar_in_place(inner, "status", "Verified");
1770        let b = yamlish::set_scalar_in_place(&b, "verified", &stamp);
1771        let b = yamlish::set_scalar_in_place(&b, "claimed_by", "—");
1772        let b = yamlish::set_scalar_in_place(&b, "claim_expires", "—");
1773        yamlish::set_map_in_place(&b, "trace", &trace_map)
1774    })?;
1775    Ok(())
1776}
1777
1778#[cfg(test)]
1779mod tests {
1780    use super::*;
1781    use vitrify_core::cascade::SddOwnership;
1782
1783    fn strings(v: &[&str]) -> Vec<String> {
1784        v.iter().map(|s| s.to_string()).collect()
1785    }
1786
1787    #[test]
1788    fn a_gate_reads_test_paths_of_its_own_sdd_only() {
1789        let ownership = Ownership::new(vec![
1790            SddOwnership {
1791                slug: "a".into(),
1792                tests: strings(&["t/a/"]),
1793                units: vec![("U-001".into(), strings(&["src/a.rs", "t/a/own.rs"]))],
1794                ..Default::default()
1795            },
1796            SddOwnership {
1797                slug: "b".into(),
1798                units: vec![("U-001".into(), strings(&["src/b.rs"]))],
1799                ..Default::default()
1800            },
1801        ]);
1802        let footprint = |slug: &str, checked: &[Node]| Footprint {
1803            slug: slug.into(),
1804            checked: checked.iter().cloned().collect(),
1805            suite: true,
1806            ownership: ownership.clone(),
1807            spec: SpecFiles::default(),
1808        };
1809        // b's gate checked a U-001's code, never a's tests
1810        let b = footprint("b", &[Node::new("b", "U-001"), Node::new("a", "U-001")]);
1811        assert!(b.reads("src/a.rs"));
1812        assert!(!b.reads("t/a/own.rs"));
1813        assert!(!b.reads("t/a/pre.rs"));
1814        // a's own gate reads both its generated and its pre-existing test
1815        let a = footprint("a", &[Node::new("a", "U-001")]);
1816        assert!(a.reads("t/a/own.rs"));
1817        assert!(a.reads("t/a/pre.rs"));
1818    }
1819}