use std::path::{Path, PathBuf};
use vitrify_core::model::{self, Instance, Shape};
use vitrify_core::writeset::WriteSet;
use vitrify_core::{CoreError, journal, trace, yamlish};
use crate::cmd::resolve_sdd_in;
use crate::git::Git;
use crate::layout;
const ABANDONED: &str = "sdd: abandoned attempt";
const JUDGED: [&str; 5] = [
"rejected-gate",
"rejected-write-set",
"ownership-conflict",
"blocked",
"released",
];
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Attempt {
pub unit: String,
pub branch: String,
pub seq: i64,
pub commit: String,
pub fork: String,
pub paths: Vec<String>,
pub sdd_rel: PathBuf,
pub built: String,
pub trace: Vec<(String, String)>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Refusal {
NoBranch,
Judged { branch: String, outcome: String },
NotBuilt { branch: String, status: String },
WriteSet { branch: String, paths: Vec<String> },
TraceMoved { branch: String, keys: Vec<String> },
}
impl Refusal {
pub fn describe(&self) -> String {
match self {
Refusal::NoBranch => "no attempt since it was last verified".to_string(),
Refusal::Judged { branch, outcome } => {
format!("its newest attempt ({branch}) was set aside as {outcome}")
}
Refusal::NotBuilt { branch, status } => {
format!("its newest attempt ({branch}) is not stamped Built (status {status})")
}
Refusal::WriteSet { branch, paths } => format!(
"its newest attempt ({branch}) changed paths outside the unit's write-set: {}",
paths.join(", ")
),
Refusal::TraceMoved { branch, keys } => format!(
"its newest attempt ({branch}) was built from inputs that have moved: {}",
keys.join(", ")
),
}
}
}
pub fn adoptable(
git: &Git,
inst: &Instance,
root: &Path,
unit: &str,
) -> Result<Result<Attempt, Refusal>, CoreError> {
let Some(u) = inst.unit(unit) else {
return Err(CoreError::refusal(
4,
format!("error: unit {unit} not found at the mainline head"),
));
};
let slug = layout::sdd_slug(inst);
let Some((seq, branch)) = newest_attempt(git, inst, &slug, unit)? else {
return Ok(Err(Refusal::NoBranch));
};
let commit = git.rev_parse(&branch).map_err(CoreError::from)?;
let message = git.commit_message(&commit).unwrap_or_default();
let subject = message.lines().next().unwrap_or("");
if let Some(rest) = subject.strip_prefix(ABANDONED)
&& let Some((_, outcome)) = rest.rsplit_once(" — ")
&& JUDGED.contains(&outcome.trim())
{
return Ok(Err(Refusal::Judged {
branch,
outcome: outcome.trim().to_string(),
}));
}
let ws = WriteSet::of(inst, u, root)?;
let stamped = git
.show_text(&commit, &ws.spec_file)
.map_err(CoreError::from)?
.and_then(|text| unit_meta_in(inst.shape, &text, unit))
.unwrap_or_default();
let status = stamped.get_str_or("status", "Draft").to_string();
let recorded = stamped.get_map("trace").cloned().unwrap_or_default();
let built = stamped.get_str_or("built", "").trim().to_string();
if status != "Built" || recorded.is_empty() {
return Ok(Err(Refusal::NotBuilt {
branch,
status: if recorded.is_empty() && status == "Built" {
"Built, no trace".to_string()
} else {
status
},
}));
}
let head = git.at(root).rev_parse("HEAD").map_err(CoreError::from)?;
let fork = git.merge_base(&head, &commit).map_err(CoreError::from)?;
let changed = git.changed_paths(&fork, &commit).map_err(CoreError::from)?;
let versions = || {
(
git.show_text(&fork, &ws.spec_file).ok().flatten(),
git.show_text(&commit, &ws.spec_file).ok().flatten(),
)
};
let mut outside: Vec<String> = ws
.violations(&changed, versions)
.iter()
.map(|v| v.path().to_string())
.collect();
if !outside.is_empty() {
outside.sort();
outside.dedup();
return Ok(Err(Refusal::WriteSet {
branch,
paths: outside,
}));
}
let (current, problems) = trace::compute(inst, u)?;
if !problems.is_empty() {
return Err(CoreError::refusal(
4,
problems
.iter()
.map(|p| format!("error: {p}"))
.collect::<Vec<_>>()
.join("\n"),
));
}
let mut keys: Vec<String> = trace::verify(&recorded, ¤t)
.into_iter()
.map(|m| m.key)
.collect();
if !keys.is_empty() {
keys.sort();
keys.dedup();
return Ok(Err(Refusal::TraceMoved { branch, keys }));
}
let mut paths: Vec<String> = changed.into_iter().filter(|p| ws.covers(p)).collect();
paths.sort();
paths.dedup();
let sdd_rel = inst
.root
.strip_prefix(root)
.map(Path::to_path_buf)
.unwrap_or_else(|_| inst.root.clone());
Ok(Ok(Attempt {
unit: unit.to_string(),
branch,
seq,
commit,
fork,
paths,
sdd_rel,
built,
trace: recorded,
}))
}
pub fn relabel(
primary: &Git,
slug: &str,
attempt: &Attempt,
new_seq: i64,
claim_commit: &str,
scratch: &Path,
) -> Result<String, CoreError> {
let refuse = |why: String| {
Err(CoreError::refusal(
1,
format!(
"error: cannot adopt {} (c{}) under claim c{new_seq}: {why}",
attempt.unit, attempt.seq
),
))
};
if new_seq <= attempt.seq {
return refuse("the new claim must supersede it".to_string());
}
let branch = layout::unit_branch(slug, &attempt.unit, new_seq);
if primary.branch_exists(&branch).map_err(CoreError::from)? {
return refuse(format!("branch {branch} already exists"));
}
if scratch.exists() {
return refuse(format!("{} already exists", scratch.display()));
}
if let Some(parent) = scratch.parent() {
fs_err::create_dir_all(parent).map_err(|source| CoreError::Io {
path: parent.to_path_buf(),
source,
})?;
}
primary
.worktree_add_branch(scratch, &branch, claim_commit)
.map_err(CoreError::from)?;
let carried = carry(primary, attempt, new_seq, scratch);
let _ = primary.worktree_remove(scratch);
if let Err(e) = carried {
let _ = primary.delete_branch(&branch);
return Err(e);
}
Ok(branch)
}
fn carry(primary: &Git, attempt: &Attempt, new_seq: i64, scratch: &Path) -> Result<(), CoreError> {
let wt = primary.at(scratch);
let mut present: Vec<String> = Vec::new();
let mut gone: Vec<String> = Vec::new();
for p in &attempt.paths {
let there = wt
.verify_ref(&format!("{}:{p}", attempt.commit))
.map_err(CoreError::from)?;
if there.is_some() {
present.push(p.clone());
} else {
gone.push(p.clone());
}
}
wt.restore_paths(&attempt.commit, &present)
.map_err(CoreError::from)?;
for p in &gone {
let path = scratch.join(p);
if path.exists() {
fs_err::remove_file(&path).map_err(|source| CoreError::Io {
path: path.clone(),
source,
})?;
}
}
let inst = Instance::load(resolve_sdd_in(scratch, &attempt.sdd_rel)?)?;
let Some(unit) = inst.unit(&attempt.unit) else {
return Err(CoreError::refusal(
4,
format!(
"error: unit {} not found at the new claim's commit",
attempt.unit
),
));
};
model::rewrite_unit_meta(&inst.handle(), unit, |inner| {
let b = yamlish::set_scalar_in_place(inner, "status", "Built");
let b = yamlish::set_scalar_in_place(&b, "built", &attempt.built);
yamlish::set_map_in_place(&b, "trace", &attempt.trace)
})?;
wt.add_all().map_err(CoreError::from)?;
wt.commit_note(
&format!(
"sdd: adopt {} (c{}) as c{new_seq}",
attempt.unit, attempt.seq
),
&format!(
"Built work of {} adopted from {} ({}), with no worker session.",
attempt.unit,
attempt.branch,
&attempt.commit[..7.min(attempt.commit.len())]
),
)
.map_err(CoreError::from)
}
fn newest_attempt(
git: &Git,
inst: &Instance,
slug: &str,
unit: &str,
) -> Result<Option<(i64, String)>, CoreError> {
let (events, _) = journal::read(&inst.handle())?;
let verified_at = events
.iter()
.filter(|e| e.event == "verified" && e.unit.as_deref() == Some(unit))
.filter_map(|e| e.claim_seq)
.max()
.unwrap_or(0);
let mut best: Option<(i64, String)> = None;
for branch in git
.branches_under(&layout::branch_prefix(slug, unit))
.map_err(CoreError::from)?
{
let Some(seq) = layout::branch_seq(&branch) else {
continue;
};
if seq > verified_at && best.as_ref().is_none_or(|(s, _)| seq > *s) {
best = Some((seq, branch));
}
}
Ok(best)
}
fn unit_meta_in(shape: Shape, text: &str, uid: &str) -> Option<model::Meta> {
match shape {
Shape::Bundle => model::front_matter(text),
Shape::Single => {
let (start, end) = model::find_unit_span(text, uid)?;
let region = &text[start..end];
let (_, _, inner_start, inner_end) = model::find_meta_block_span(region)?;
Some(model::Meta(yamlish::parse(®ion[inner_start..inner_end])))
}
}
}