1use std::path::{Path, PathBuf};
12
13use vitrify_core::claims::Op;
14use vitrify_core::model::{self, Instance, UtcTime};
15use vitrify_core::{CoreError, audit, journal, ledger, questions, yamlish};
16
17use crate::cli::ClaimArgs;
18use crate::cmd::{self, claim};
19use crate::gate::ShRunner;
20use crate::git::{Git, GitError};
21use crate::layout::Layout;
22use crate::signals;
23
24#[derive(Debug, Clone)]
25pub struct Mainline {
26 pub primary: Git,
28 pub layout: Layout,
29 pub sdd_rel: PathBuf,
31 pub slug: String,
33 pub branch: String,
35 pub push: bool,
37}
38
39pub struct LaneLock(std::fs::File);
42
43impl Drop for LaneLock {
44 fn drop(&mut self) {
49 let _ = self.0.unlock();
50 }
51}
52
53#[derive(Debug, Clone)]
55pub struct Landed {
56 pub commit: String,
57 pub local_was: Option<String>,
60}
61
62#[derive(Debug, Default, Clone)]
64pub struct Healed {
65 pub leases: Vec<String>,
67 pub stale: Vec<(String, String)>,
69 pub other: Vec<audit::Finding>,
71 pub commit: Option<String>,
73}
74
75impl Mainline {
76 pub fn head(&self) -> Result<String, CoreError> {
78 let name = if self.push {
79 let _ = self.primary.fetch_origin(&self.branch);
80 format!("refs/remotes/origin/{}", self.branch)
81 } else {
82 format!("refs/heads/{}", self.branch)
83 };
84 self.primary.rev_parse(&name).map_err(CoreError::from)
85 }
86
87 pub fn sdd_in(&self, checkout: &Path) -> Result<Instance, CoreError> {
89 Instance::load(cmd::resolve_sdd_in(checkout, &self.sdd_rel)?)
90 }
91
92 pub fn claim(
96 &self,
97 op: Op,
98 unit: &str,
99 holder: &str,
100 lease_minutes: i64,
101 ) -> Result<claim::ClaimOutcome, CoreError> {
102 let args = ClaimArgs {
103 unit: unit.to_string(),
104 holder: holder.to_string(),
105 lease_minutes,
106 sdd: None,
107 mainline: Some(self.branch.clone()),
108 };
109 claim::execute_pinned(
110 op,
111 &args,
112 &claim::Pinned {
113 push: self.push,
114 sdd_rel: &self.sdd_rel,
115 },
116 )
117 }
118
119 pub fn checkout(&self) -> PathBuf {
121 self.layout.mainline(&self.slug)
122 }
123
124 pub fn lock_checkout(&self, waiting: &dyn Fn()) -> Result<Option<LaneLock>, CoreError> {
128 let path = self.layout.mainline_lock(&self.slug);
129 let io = |source| CoreError::Io {
130 path: path.clone(),
131 source,
132 };
133 if let Some(parent) = path.parent() {
134 std::fs::create_dir_all(parent).map_err(io)?;
135 }
136 let file = std::fs::OpenOptions::new()
137 .create(true)
138 .truncate(false)
139 .write(true)
140 .open(&path)
141 .map_err(io)?;
142 let mut told = false;
143 loop {
144 match file.try_lock() {
145 Ok(()) => return Ok(Some(LaneLock(file))),
146 Err(std::fs::TryLockError::WouldBlock) => {
147 if signals::interrupted() {
148 return Ok(None);
149 }
150 if !told {
151 waiting();
152 told = true;
153 }
154 std::thread::sleep(std::time::Duration::from_millis(250));
155 }
156 Err(std::fs::TryLockError::Error(e)) => return Err(io(e)),
157 }
158 }
159 }
160
161 pub fn remove_checkouts(&self) {
166 let Ok(Some(_held)) = self.lock_checkout(&|| {}) else {
167 return;
168 };
169 let _turn = claim::tx_lock();
170 for path in [
171 self.checkout(),
172 self.layout.base_checkout(&self.slug),
173 self.layout.wt_root.join(format!("probe-{}", self.slug)),
174 ] {
175 if path.exists() {
176 let _ = self.primary.worktree_remove(&path);
177 }
178 if path.exists() {
179 let _ = std::fs::remove_dir_all(&path);
180 let _ = self.primary.worktree_remove(&path);
181 }
182 }
183 }
184
185 pub fn recreate_checkout(&self, rev: &str) -> Result<PathBuf, CoreError> {
191 let path = self.checkout();
192 let _turn = claim::tx_lock();
194 if path.exists() {
195 let _ = self.primary.worktree_remove(&path);
198 }
199 if path.exists() {
200 std::fs::remove_dir_all(&path).map_err(|source| CoreError::Io {
203 path: path.clone(),
204 source,
205 })?;
206 let _ = self.primary.worktree_remove(&path);
207 }
208 self.pristine(&path, rev)?;
209 Ok(path)
210 }
211
212 pub fn sync_checkout(&self, path: &Path) -> Result<String, CoreError> {
215 let head = self.head()?;
216 self.pristine(path, &head)?;
217 Ok(head)
218 }
219
220 pub fn pristine(&self, path: &Path, rev: &str) -> Result<(), CoreError> {
227 if path.join(".git").exists() {
228 let wt = self.primary.at(path);
229 let _ = wt.merge_abort();
231 wt.reset_hard(rev).map_err(CoreError::from)?;
232 wt.clean_all().map_err(CoreError::from)?;
233 } else {
234 if let Some(parent) = path.parent() {
235 std::fs::create_dir_all(parent).map_err(|source| CoreError::Io {
236 path: parent.to_path_buf(),
237 source,
238 })?;
239 }
240 self.primary
241 .worktree_add(path, rev, true)
242 .map_err(CoreError::from)?;
243 }
244 Ok(())
245 }
246
247 pub fn publish(&self, new: &str, base: &str) -> Result<Option<Landed>, CoreError> {
250 let local = format!("refs/heads/{}", self.branch);
251 if self.push {
252 match self.primary.push_cas(new, &self.branch) {
253 Ok(()) => {
254 let mut local_was = None;
256 if let Some(cur) = self.primary.verify_ref(&local).map_err(CoreError::from)?
257 && self
258 .primary
259 .is_ancestor(&cur, new)
260 .map_err(CoreError::from)?
261 && self.primary.update_ref_cas(&local, new, &cur).is_ok()
262 {
263 local_was = Some(cur);
264 }
265 Ok(Some(Landed {
266 commit: new.to_string(),
267 local_was,
268 }))
269 }
270 Err(GitError::LostRace { .. }) => Ok(None),
271 Err(e) => Err(e.into()),
272 }
273 } else {
274 match self.primary.update_ref_cas(&local, new, base) {
275 Ok(()) => Ok(Some(Landed {
276 commit: new.to_string(),
277 local_was: Some(base.to_string()),
278 })),
279 Err(GitError::LostRace { .. }) => Ok(None),
280 Err(e) => Err(e.into()),
281 }
282 }
283 }
284
285 pub fn follow(&self, landed: &Landed) -> Result<(), CoreError> {
288 match &landed.local_was {
289 Some(was) => claim::resync_primary(&self.primary, &self.branch, was, &landed.commit),
290 None => Ok(()),
291 }
292 }
293
294 pub fn publish_tx(
301 &self,
302 commit_message: &str,
303 build: &dyn Fn(&Path) -> Result<bool, CoreError>,
304 ) -> Result<Option<String>, CoreError> {
305 self.layout.ensure_scratch()?;
306 let _turn = claim::tx_lock();
307 let tx = self.layout.scratch.join(format!(
308 "tx-{}-orch{}",
309 std::process::id(),
310 UtcTime::now().0
311 ));
312 let result = (|| {
313 for attempt in 0..6u64 {
314 if attempt > 0 {
315 std::thread::sleep(std::time::Duration::from_millis(100 * attempt));
316 }
317 let base = self.head()?;
318 self.pristine(&tx, &base)?;
319 if !build(&tx)? {
320 return Ok(None);
321 }
322 let txgit = self.primary.at(&tx);
323 txgit.add_all().map_err(CoreError::from)?;
324 txgit.commit(commit_message).map_err(CoreError::from)?;
325 let new = txgit.rev_parse("HEAD").map_err(CoreError::from)?;
326 if let Some(landed) = self.publish(&new, &base)? {
327 self.follow(&landed)?;
328 return Ok(Some(new));
329 }
330 }
331 Err(CoreError::refusal(
332 5,
333 format!("error: lost publish race for `{commit_message}` after retries"),
334 ))
335 })();
336 if tx.exists() {
337 let _ = self.primary.worktree_remove(&tx);
338 }
339 result
340 }
341
342 pub fn heal(&self, fix_leases: bool, apply_stale: bool) -> Result<Healed, CoreError> {
349 let healed = std::cell::RefCell::new(Healed::default());
350 let message = match (fix_leases, apply_stale) {
351 (true, true) => "sdd: audit --fix-leases --apply-stale",
352 (false, true) => "sdd: audit --apply-stale",
353 _ => "sdd: audit --fix-leases",
354 };
355 let commit = self.publish_tx(message, &|tx| {
356 let inst = self.sdd_in(tx)?;
357 let (findings, edits) = audit::run(
358 &inst,
359 tx,
360 &cmd::audit_options(
361 audit::Options {
362 skip_rotten: true,
363 fix_leases,
364 apply_stale,
365 ..Default::default()
366 },
367 tx,
368 &inst,
369 ),
370 &ShRunner,
371 UtcTime::now(),
372 )?;
373 let mut h = Healed::default();
374 for edit in &edits {
375 match edit {
376 audit::StateEdit::FixLease { unit, .. } => h.leases.push(unit.clone()),
377 audit::StateEdit::ApplyStale { unit, cause } => {
378 h.stale.push((unit.clone(), cause.clone()))
379 }
380 }
381 }
382 let fixed = |f: &audit::Finding| {
383 (f.check == 7 && h.leases.contains(&f.subject))
384 || (f.check == 5 && h.stale.iter().any(|(u, _)| u == &f.subject))
385 };
386 h.other = findings.into_iter().filter(|f| !fixed(f)).collect();
387 let changed = !edits.is_empty();
388 if changed {
389 cmd::audit::apply_edits(&inst, &edits)?;
390 let fresh = Instance::load(inst.handle())?;
391 ledger::regen(&fresh, &UtcTime::now().format_date())?;
392 }
393 *healed.borrow_mut() = h;
394 Ok(changed)
395 })?;
396 let mut healed = healed.into_inner();
397 healed.commit = commit;
398 Ok(healed)
399 }
400
401 pub fn land_q_entry(
407 &self,
408 q: &str,
409 unit: &str,
410 holder: &str,
411 notes: &str,
412 ) -> Result<(), CoreError> {
413 let notes = notes.replace('\n', " ");
414 self.publish_tx(&format!("sdd: record {q} (blocked {unit})"), &|tx| {
415 let inst = self.sdd_in(tx)?;
416 let entry =
417 questions::landed_entry(q, &UtcTime::now().format_date(), holder, unit, ¬es);
418 match inst.shape {
419 model::Shape::Bundle => {
420 let path = inst.root.join("decisions.md");
421 let text = std::fs::read_to_string(&path)
422 .unwrap_or_else(|_| "# Decisions & Open Questions\n".to_string());
423 if text.contains(&format!("**{q}**")) {
424 return Ok(false); }
426 model::write_text(&path, &questions::land(&text, &entry))?;
427 }
428 model::Shape::Single => {
429 let text = model::read_text(&inst.file)?;
430 if text.contains(&format!("**{q}**")) {
431 return Ok(false);
432 }
433 let new = match model::section_span(&text, "Decisions & Open Questions") {
434 Some((s, e)) => format!(
435 "{}{}{}",
436 &text[..s],
437 questions::land(&text[s..e], &entry),
438 &text[e..]
439 ),
440 None => format!(
441 "{}\n\n## Decisions & Open Questions\n\n{entry}",
442 text.trim_end_matches('\n')
443 ),
444 };
445 model::write_text(&inst.file, &new)?;
446 }
447 }
448 Ok(true)
449 })?;
450 Ok(())
451 }
452}
453
454pub fn append_event(inst: &Instance, mut event: journal::Event) -> Result<(), CoreError> {
456 let handle = inst.handle();
457 let (events, _) = journal::read(&handle)?;
458 event.seq = events.last().map(|e| e.seq).unwrap_or(0) + 1;
459 if event.at.is_empty() {
460 event.at = UtcTime::now().format();
461 }
462 if event.sdd.is_empty() {
463 event.sdd = inst.meta.get_str_or("version", "0.0.0").to_string();
464 }
465 journal::append_line(&handle, &journal::render_line(&event))?;
466 Ok(())
467}
468
469pub fn released_meta(inner: &str) -> String {
471 let b = yamlish::set_scalar_in_place(inner, "status", "Ready");
472 let b = yamlish::set_scalar_in_place(&b, "claimed_by", "—");
473 yamlish::set_scalar_in_place(&b, "claim_expires", "—")
474}