1use 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 pub primary: Git,
26 pub layout: Layout,
27 pub sdd_rel: PathBuf,
29 pub branch: String,
31 pub push: bool,
33}
34
35#[derive(Debug, Clone)]
37pub struct Landed {
38 pub commit: String,
39 pub local_was: Option<String>,
42}
43
44#[derive(Debug, Default, Clone)]
46pub struct Healed {
47 pub leases: Vec<String>,
49 pub stale: Vec<(String, String)>,
51 pub other: Vec<audit::Finding>,
53 pub commit: Option<String>,
55}
56
57impl Mainline {
58 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 pub fn sdd_in(&self, checkout: &Path) -> Result<Instance, CoreError> {
71 Instance::load(cmd::resolve_sdd_in(checkout, &self.sdd_rel)?)
72 }
73
74 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 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 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 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 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 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 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 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 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 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, ¬es);
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); }
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
339pub 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
354pub 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}