Skip to main content

vitrify_cli/run/
mainline.rs

1//! The run's handle on mainline: which repository, which SDD, which branch,
2//! and how a commit gets there.
3//!
4//! The SDD is pinned by its path relative to the repository root, resolved
5//! once in preflight. Every later read — in the primary checkout, a unit
6//! worktree, the integration checkout or a transaction — resolves that same
7//! path and never searches, so a repository with several SDDs is as
8//! unambiguous after preflight as it was during it.
9
10use std::path::{Path, PathBuf};
11
12use vitrify_core::claims::Op;
13use vitrify_core::model::{self, Instance, UtcTime};
14use vitrify_core::{CoreError, audit, journal, ledger, questions, yamlish};
15
16use crate::cli::ClaimArgs;
17use crate::cmd::{self, claim};
18use crate::gate::ShRunner;
19use crate::git::{Git, GitError};
20use crate::layout::Layout;
21
22#[derive(Debug, Clone)]
23pub struct Mainline {
24    /// The primary checkout.
25    pub primary: Git,
26    pub layout: Layout,
27    /// The SDD's root relative to the repository root.
28    pub sdd_rel: PathBuf,
29    /// The mainline branch.
30    pub branch: String,
31    /// Publish by `git push` (origin arbitrates) rather than a local CAS.
32    pub push: bool,
33}
34
35/// A commit that reached mainline.
36#[derive(Debug, Clone)]
37pub struct Landed {
38    pub commit: String,
39    /// What the local branch pointed at before it was moved to the commit;
40    /// `None` when it was not moved (it has diverged from origin's).
41    pub local_was: Option<String>,
42}
43
44/// What [`Mainline::heal`] put right.
45#[derive(Debug, Default, Clone)]
46pub struct Healed {
47    /// Units whose lapsed lease was released.
48    pub leases: Vec<String>,
49    /// Units marked Stale, each with the cause.
50    pub stale: Vec<(String, String)>,
51    /// Findings the audit cannot fix itself.
52    pub other: Vec<audit::Finding>,
53    /// The published commit, when anything changed.
54    pub commit: Option<String>,
55}
56
57impl Mainline {
58    /// The mainline head (fetched first when origin arbitrates).
59    pub fn head(&self) -> Result<String, CoreError> {
60        let name = if self.push {
61            let _ = self.primary.fetch_origin(&self.branch);
62            format!("refs/remotes/origin/{}", self.branch)
63        } else {
64            format!("refs/heads/{}", self.branch)
65        };
66        self.primary.rev_parse(&name).map_err(CoreError::from)
67    }
68
69    /// The pinned SDD as `checkout` holds it.
70    pub fn sdd_in(&self, checkout: &Path) -> Result<Instance, CoreError> {
71        Instance::load(cmd::resolve_sdd_in(checkout, &self.sdd_rel)?)
72    }
73
74    /// One claim transaction on this run's SDD — published the way this run
75    /// publishes, on the SDD this run pinned, wherever the process's
76    /// working directory happens to be.
77    pub fn claim(
78        &self,
79        op: Op,
80        unit: &str,
81        holder: &str,
82        lease_minutes: i64,
83    ) -> Result<claim::ClaimOutcome, CoreError> {
84        let args = ClaimArgs {
85            unit: unit.to_string(),
86            holder: holder.to_string(),
87            lease_minutes,
88            sdd: None,
89            mainline: Some(self.branch.clone()),
90        };
91        claim::execute_pinned(
92            op,
93            &args,
94            &claim::Pinned {
95                push: self.push,
96                sdd_rel: &self.sdd_rel,
97            },
98        )
99    }
100
101    /// Bring the detached worktree at `path` to the mainline head, creating
102    /// it on first use. Returns the head.
103    pub fn sync_checkout(&self, path: &Path) -> Result<String, CoreError> {
104        let head = self.head()?;
105        self.checkout_at(path, &head)?;
106        Ok(head)
107    }
108
109    /// Bring the detached worktree at `path` to `rev`, creating it on first
110    /// use; untracked files git does not ignore are removed.
111    pub fn checkout_at(&self, path: &Path, rev: &str) -> Result<(), CoreError> {
112        if path.join(".git").exists() {
113            let wt = self.primary.at(path);
114            // an interrupted merge would refuse the reset
115            let _ = wt.merge_abort();
116            wt.reset_hard(rev).map_err(CoreError::from)?;
117            wt.clean_fdq().map_err(CoreError::from)?;
118        } else {
119            if let Some(parent) = path.parent() {
120                std::fs::create_dir_all(parent).map_err(|source| CoreError::Io {
121                    path: parent.to_path_buf(),
122                    source,
123                })?;
124            }
125            self.primary
126                .worktree_add(path, rev, true)
127                .map_err(CoreError::from)?;
128        }
129        Ok(())
130    }
131
132    /// Move mainline from `base` to `new`: a push when origin arbitrates,
133    /// else the local compare-and-swap. `None` = lost the race.
134    pub fn publish(&self, new: &str, base: &str) -> Result<Option<Landed>, CoreError> {
135        let local = format!("refs/heads/{}", self.branch);
136        if self.push {
137            match self.primary.push_cas(new, &self.branch) {
138                Ok(()) => {
139                    // the local branch follows when it can
140                    let mut local_was = None;
141                    if let Some(cur) = self.primary.verify_ref(&local).map_err(CoreError::from)?
142                        && self
143                            .primary
144                            .is_ancestor(&cur, new)
145                            .map_err(CoreError::from)?
146                        && self.primary.update_ref_cas(&local, new, &cur).is_ok()
147                    {
148                        local_was = Some(cur);
149                    }
150                    Ok(Some(Landed {
151                        commit: new.to_string(),
152                        local_was,
153                    }))
154                }
155                Err(GitError::LostRace { .. }) => Ok(None),
156                Err(e) => Err(e.into()),
157            }
158        } else {
159            match self.primary.update_ref_cas(&local, new, base) {
160                Ok(()) => Ok(Some(Landed {
161                    commit: new.to_string(),
162                    local_was: Some(base.to_string()),
163                })),
164                Err(GitError::LostRace { .. }) => Ok(None),
165                Err(e) => Err(e.into()),
166            }
167        }
168    }
169
170    /// The primary checkout follows a commit that landed — when the local
171    /// branch moved with it. Call it while still holding the mainline turn.
172    pub fn follow(&self, landed: &Landed) -> Result<(), CoreError> {
173        match &landed.local_was {
174            Some(was) => claim::resync_primary(&self.primary, &self.branch, was, &landed.commit),
175            None => Ok(()),
176        }
177    }
178
179    /// Publish one orchestrator-owned mainline commit by the claim
180    /// discipline (CAS/push, never forced). `build` edits a transaction
181    /// worktree at the head and reports whether there is anything to commit;
182    /// `None` = nothing was. A lost race rebuilds on the new head — more
183    /// patiently than a claim does: these commits have no competitor for
184    /// what they change, only for the ref.
185    pub fn publish_tx(
186        &self,
187        commit_message: &str,
188        build: &dyn Fn(&Path) -> Result<bool, CoreError>,
189    ) -> Result<Option<String>, CoreError> {
190        self.layout.ensure_scratch()?;
191        let _turn = claim::tx_lock();
192        let tx = self.layout.scratch.join(format!(
193            "tx-{}-orch{}",
194            std::process::id(),
195            UtcTime::now().0
196        ));
197        let result = (|| {
198            for attempt in 0..6u64 {
199                if attempt > 0 {
200                    std::thread::sleep(std::time::Duration::from_millis(100 * attempt));
201                }
202                let base = self.head()?;
203                self.checkout_at(&tx, &base)?;
204                if !build(&tx)? {
205                    return Ok(None);
206                }
207                let txgit = self.primary.at(&tx);
208                txgit.add_all().map_err(CoreError::from)?;
209                txgit.commit(commit_message).map_err(CoreError::from)?;
210                let new = txgit.rev_parse("HEAD").map_err(CoreError::from)?;
211                if let Some(landed) = self.publish(&new, &base)? {
212                    self.follow(&landed)?;
213                    return Ok(Some(new));
214                }
215            }
216            Err(CoreError::refusal(
217                5,
218                format!("error: lost publish race for `{commit_message}` after retries"),
219            ))
220        })();
221        if tx.exists() {
222            let _ = self.primary.worktree_remove(&tx);
223        }
224        result
225    }
226
227    /// Put right what the audit can put right mechanically, as one mainline
228    /// commit: lapsed leases are released (`fix_leases`), and Built or
229    /// Verified units whose recorded trace no longer matches their inputs
230    /// are marked Stale with the cause (`apply_stale`) — which is what makes
231    /// a spec change that lands mid-run rebuild what it touched. Everything
232    /// else the audit found is returned in `other`.
233    pub fn heal(&self, fix_leases: bool, apply_stale: bool) -> Result<Healed, CoreError> {
234        let healed = std::cell::RefCell::new(Healed::default());
235        let message = match (fix_leases, apply_stale) {
236            (true, true) => "sdd: audit --fix-leases --apply-stale",
237            (false, true) => "sdd: audit --apply-stale",
238            _ => "sdd: audit --fix-leases",
239        };
240        let commit = self.publish_tx(message, &|tx| {
241            let inst = self.sdd_in(tx)?;
242            let (findings, edits) = audit::run(
243                &inst,
244                tx,
245                &cmd::audit_options(
246                    audit::Options {
247                        skip_rotten: true,
248                        fix_leases,
249                        apply_stale,
250                        ..Default::default()
251                    },
252                    tx,
253                    &inst,
254                ),
255                &ShRunner,
256                UtcTime::now(),
257            )?;
258            let mut h = Healed::default();
259            for edit in &edits {
260                match edit {
261                    audit::StateEdit::FixLease { unit, .. } => h.leases.push(unit.clone()),
262                    audit::StateEdit::ApplyStale { unit, cause } => {
263                        h.stale.push((unit.clone(), cause.clone()))
264                    }
265                }
266            }
267            let fixed = |f: &audit::Finding| {
268                (f.check == 7 && h.leases.contains(&f.subject))
269                    || (f.check == 5 && h.stale.iter().any(|(u, _)| u == &f.subject))
270            };
271            h.other = findings.into_iter().filter(|f| !fixed(f)).collect();
272            let changed = !edits.is_empty();
273            if changed {
274                cmd::audit::apply_edits(&inst, &edits)?;
275                let fresh = Instance::load(inst.handle())?;
276                ledger::regen(&fresh, &UtcTime::now().format_date())?;
277            }
278            *healed.borrow_mut() = h;
279            Ok(changed)
280        })?;
281        let mut healed = healed.into_inner();
282        healed.commit = commit;
283        Ok(healed)
284    }
285
286    /// Land a `Q-###` Decision-Log entry as a mainline commit (a worker
287    /// reports the question; the Decision Log is outside its write-set).
288    /// The entry says `open`, as the schema's own entries do: a question is
289    /// open unless marked resolved, and one a run has just landed is not to
290    /// be read as anything else by a tool that looks for the word.
291    pub fn land_q_entry(
292        &self,
293        q: &str,
294        unit: &str,
295        holder: &str,
296        notes: &str,
297    ) -> Result<(), CoreError> {
298        let notes = notes.replace('\n', " ");
299        self.publish_tx(&format!("sdd: record {q} (blocked {unit})"), &|tx| {
300            let inst = self.sdd_in(tx)?;
301            let entry =
302                questions::landed_entry(q, &UtcTime::now().format_date(), holder, unit, &notes);
303            match inst.shape {
304                model::Shape::Bundle => {
305                    let path = inst.root.join("decisions.md");
306                    let text = std::fs::read_to_string(&path)
307                        .unwrap_or_else(|_| "# Decisions & Open Questions\n".to_string());
308                    if text.contains(&format!("**{q}**")) {
309                        return Ok(false); // already landed
310                    }
311                    model::write_text(&path, &questions::land(&text, &entry))?;
312                }
313                model::Shape::Single => {
314                    let text = model::read_text(&inst.file)?;
315                    if text.contains(&format!("**{q}**")) {
316                        return Ok(false);
317                    }
318                    let new = match model::section_span(&text, "Decisions & Open Questions") {
319                        Some((s, e)) => format!(
320                            "{}{}{}",
321                            &text[..s],
322                            questions::land(&text[s..e], &entry),
323                            &text[e..]
324                        ),
325                        None => format!(
326                            "{}\n\n## Decisions & Open Questions\n\n{entry}",
327                            text.trim_end_matches('\n')
328                        ),
329                    };
330                    model::write_text(&inst.file, &new)?;
331                }
332            }
333            Ok(true)
334        })?;
335        Ok(())
336    }
337}
338
339/// Append one journal event at the next sequence number.
340pub fn append_event(inst: &Instance, mut event: journal::Event) -> Result<(), CoreError> {
341    let handle = inst.handle();
342    let (events, _) = journal::read(&handle)?;
343    event.seq = events.last().map(|e| e.seq).unwrap_or(0) + 1;
344    if event.at.is_empty() {
345        event.at = UtcTime::now().format();
346    }
347    if event.sdd.is_empty() {
348        event.sdd = inst.meta.get_str_or("version", "0.0.0").to_string();
349    }
350    journal::append_line(&handle, &journal::render_line(&event))?;
351    Ok(())
352}
353
354/// The unit's front matter after a release: Ready, no holder, no expiry.
355pub fn released_meta(inner: &str) -> String {
356    let b = yamlish::set_scalar_in_place(inner, "status", "Ready");
357    let b = yamlish::set_scalar_in_place(&b, "claimed_by", "—");
358    yamlish::set_scalar_in_place(&b, "claim_expires", "—")
359}