1use std::path::{Path, PathBuf};
52
53use vitrify_core::model::{self, Instance, Shape};
54use vitrify_core::writeset::WriteSet;
55use vitrify_core::{CoreError, journal, trace, yamlish};
56
57use crate::cmd::resolve_sdd_in;
58use crate::git::Git;
59use crate::layout;
60
61const ABANDONED: &str = "sdd: abandoned attempt";
64
65const JUDGED: [&str; 5] = [
68 "rejected-gate",
69 "rejected-write-set",
70 "ownership-conflict",
71 "blocked",
72 "released",
73];
74
75#[derive(Debug, Clone, PartialEq, Eq)]
77pub struct Attempt {
78 pub unit: String,
79 pub branch: String,
81 pub seq: i64,
83 pub commit: String,
85 pub fork: String,
87 pub paths: Vec<String>,
90 pub sdd_rel: PathBuf,
92 pub built: String,
94 pub trace: Vec<(String, String)>,
96}
97
98#[derive(Debug, Clone, PartialEq, Eq)]
100pub enum Refusal {
101 NoBranch,
103 Judged { branch: String, outcome: String },
105 NotBuilt { branch: String, status: String },
107 WriteSet { branch: String, paths: Vec<String> },
109 TraceMoved { branch: String, keys: Vec<String> },
112}
113
114impl Refusal {
115 pub fn describe(&self) -> String {
117 match self {
118 Refusal::NoBranch => "no attempt since it was last verified".to_string(),
119 Refusal::Judged { branch, outcome } => {
120 format!("its newest attempt ({branch}) was set aside as {outcome}")
121 }
122 Refusal::NotBuilt { branch, status } => {
123 format!("its newest attempt ({branch}) is not stamped Built (status {status})")
124 }
125 Refusal::WriteSet { branch, paths } => format!(
126 "its newest attempt ({branch}) changed paths outside the unit's write-set: {}",
127 paths.join(", ")
128 ),
129 Refusal::TraceMoved { branch, keys } => format!(
130 "its newest attempt ({branch}) was built from inputs that have moved: {}",
131 keys.join(", ")
132 ),
133 }
134 }
135}
136
137pub fn adoptable(
143 git: &Git,
144 inst: &Instance,
145 root: &Path,
146 unit: &str,
147) -> Result<Result<Attempt, Refusal>, CoreError> {
148 let Some(u) = inst.unit(unit) else {
149 return Err(CoreError::refusal(
150 4,
151 format!("error: unit {unit} not found at the mainline head"),
152 ));
153 };
154 let slug = layout::sdd_slug(inst);
155 let Some((seq, branch)) = newest_attempt(git, inst, &slug, unit)? else {
156 return Ok(Err(Refusal::NoBranch));
157 };
158 let commit = git.rev_parse(&branch).map_err(CoreError::from)?;
159 let message = git.commit_message(&commit).unwrap_or_default();
160 let subject = message.lines().next().unwrap_or("");
161 if let Some(rest) = subject.strip_prefix(ABANDONED)
162 && let Some((_, outcome)) = rest.rsplit_once(" — ")
163 && JUDGED.contains(&outcome.trim())
164 {
165 return Ok(Err(Refusal::Judged {
166 branch,
167 outcome: outcome.trim().to_string(),
168 }));
169 }
170 let ws = WriteSet::of(inst, u, root)?;
172 let stamped = git
173 .show_text(&commit, &ws.spec_file)
174 .map_err(CoreError::from)?
175 .and_then(|text| unit_meta_in(inst.shape, &text, unit))
176 .unwrap_or_default();
177 let status = stamped.get_str_or("status", "Draft").to_string();
178 let recorded = stamped.get_map("trace").cloned().unwrap_or_default();
179 let built = stamped.get_str_or("built", "").trim().to_string();
180 if status != "Built" || recorded.is_empty() {
181 return Ok(Err(Refusal::NotBuilt {
182 branch,
183 status: if recorded.is_empty() && status == "Built" {
184 "Built, no trace".to_string()
185 } else {
186 status
187 },
188 }));
189 }
190 let head = git.at(root).rev_parse("HEAD").map_err(CoreError::from)?;
193 let fork = git.merge_base(&head, &commit).map_err(CoreError::from)?;
194 let changed = git.changed_paths(&fork, &commit).map_err(CoreError::from)?;
195 let versions = || {
196 (
197 git.show_text(&fork, &ws.spec_file).ok().flatten(),
198 git.show_text(&commit, &ws.spec_file).ok().flatten(),
199 )
200 };
201 let mut outside: Vec<String> = ws
202 .violations(&changed, versions)
203 .iter()
204 .map(|v| v.path().to_string())
205 .collect();
206 if !outside.is_empty() {
207 outside.sort();
208 outside.dedup();
209 return Ok(Err(Refusal::WriteSet {
210 branch,
211 paths: outside,
212 }));
213 }
214 let (current, problems) = trace::compute(inst, u)?;
216 if !problems.is_empty() {
217 return Err(CoreError::refusal(
218 4,
219 problems
220 .iter()
221 .map(|p| format!("error: {p}"))
222 .collect::<Vec<_>>()
223 .join("\n"),
224 ));
225 }
226 let mut keys: Vec<String> = trace::verify(&recorded, ¤t)
227 .into_iter()
228 .map(|m| m.key)
229 .collect();
230 if !keys.is_empty() {
231 keys.sort();
232 keys.dedup();
233 return Ok(Err(Refusal::TraceMoved { branch, keys }));
234 }
235 let mut paths: Vec<String> = changed.into_iter().filter(|p| ws.covers(p)).collect();
236 paths.sort();
237 paths.dedup();
238 let sdd_rel = inst
239 .root
240 .strip_prefix(root)
241 .map(Path::to_path_buf)
242 .unwrap_or_else(|_| inst.root.clone());
243 Ok(Ok(Attempt {
244 unit: unit.to_string(),
245 branch,
246 seq,
247 commit,
248 fork,
249 paths,
250 sdd_rel,
251 built,
252 trace: recorded,
253 }))
254}
255
256pub fn relabel(
268 primary: &Git,
269 slug: &str,
270 attempt: &Attempt,
271 new_seq: i64,
272 claim_commit: &str,
273 scratch: &Path,
274) -> Result<String, CoreError> {
275 let refuse = |why: String| {
276 Err(CoreError::refusal(
277 1,
278 format!(
279 "error: cannot adopt {} (c{}) under claim c{new_seq}: {why}",
280 attempt.unit, attempt.seq
281 ),
282 ))
283 };
284 if new_seq <= attempt.seq {
285 return refuse("the new claim must supersede it".to_string());
286 }
287 let branch = layout::unit_branch(slug, &attempt.unit, new_seq);
288 if primary.branch_exists(&branch).map_err(CoreError::from)? {
289 return refuse(format!("branch {branch} already exists"));
290 }
291 if scratch.exists() {
292 return refuse(format!("{} already exists", scratch.display()));
293 }
294 if let Some(parent) = scratch.parent() {
295 fs_err::create_dir_all(parent).map_err(|source| CoreError::Io {
296 path: parent.to_path_buf(),
297 source,
298 })?;
299 }
300 primary
301 .worktree_add_branch(scratch, &branch, claim_commit)
302 .map_err(CoreError::from)?;
303 let carried = carry(primary, attempt, new_seq, scratch);
304 let _ = primary.worktree_remove(scratch);
305 if let Err(e) = carried {
306 let _ = primary.delete_branch(&branch);
307 return Err(e);
308 }
309 Ok(branch)
310}
311
312fn carry(primary: &Git, attempt: &Attempt, new_seq: i64, scratch: &Path) -> Result<(), CoreError> {
314 let wt = primary.at(scratch);
315 let mut present: Vec<String> = Vec::new();
316 let mut gone: Vec<String> = Vec::new();
317 for p in &attempt.paths {
318 let there = wt
319 .verify_ref(&format!("{}:{p}", attempt.commit))
320 .map_err(CoreError::from)?;
321 if there.is_some() {
322 present.push(p.clone());
323 } else {
324 gone.push(p.clone());
325 }
326 }
327 wt.restore_paths(&attempt.commit, &present)
328 .map_err(CoreError::from)?;
329 for p in &gone {
330 let path = scratch.join(p);
331 if path.exists() {
332 fs_err::remove_file(&path).map_err(|source| CoreError::Io {
333 path: path.clone(),
334 source,
335 })?;
336 }
337 }
338 let inst = Instance::load(resolve_sdd_in(scratch, &attempt.sdd_rel)?)?;
340 let Some(unit) = inst.unit(&attempt.unit) else {
341 return Err(CoreError::refusal(
342 4,
343 format!(
344 "error: unit {} not found at the new claim's commit",
345 attempt.unit
346 ),
347 ));
348 };
349 model::rewrite_unit_meta(&inst.handle(), unit, |inner| {
350 let b = yamlish::set_scalar_in_place(inner, "status", "Built");
351 let b = yamlish::set_scalar_in_place(&b, "built", &attempt.built);
352 yamlish::set_map_in_place(&b, "trace", &attempt.trace)
353 })?;
354 wt.add_all().map_err(CoreError::from)?;
355 wt.commit_note(
356 &format!(
357 "sdd: adopt {} (c{}) as c{new_seq}",
358 attempt.unit, attempt.seq
359 ),
360 &format!(
361 "Built work of {} adopted from {} ({}), with no worker session.",
362 attempt.unit,
363 attempt.branch,
364 &attempt.commit[..7.min(attempt.commit.len())]
365 ),
366 )
367 .map_err(CoreError::from)
368}
369
370fn newest_attempt(
374 git: &Git,
375 inst: &Instance,
376 slug: &str,
377 unit: &str,
378) -> Result<Option<(i64, String)>, CoreError> {
379 let (events, _) = journal::read(&inst.handle())?;
380 let verified_at = events
381 .iter()
382 .filter(|e| e.event == "verified" && e.unit.as_deref() == Some(unit))
383 .filter_map(|e| e.claim_seq)
384 .max()
385 .unwrap_or(0);
386 let mut best: Option<(i64, String)> = None;
387 for branch in git
388 .branches_under(&layout::branch_prefix(slug, unit))
389 .map_err(CoreError::from)?
390 {
391 let Some(seq) = layout::branch_seq(&branch) else {
392 continue;
393 };
394 if seq > verified_at && best.as_ref().is_none_or(|(s, _)| seq > *s) {
395 best = Some((seq, branch));
396 }
397 }
398 Ok(best)
399}
400
401fn unit_meta_in(shape: Shape, text: &str, uid: &str) -> Option<model::Meta> {
404 match shape {
405 Shape::Bundle => model::front_matter(text),
406 Shape::Single => {
407 let (start, end) = model::find_unit_span(text, uid)?;
408 let region = &text[start..end];
409 let (_, _, inner_start, inner_end) = model::find_meta_block_span(region)?;
410 Some(model::Meta(yamlish::parse(®ion[inner_start..inner_end])))
411 }
412 }
413}