1use std::path::Path;
13
14use vitrify_core::model::Instance;
15use vitrify_core::writeset::WriteSet;
16use vitrify_core::{CoreError, journal};
17
18use crate::git::Git;
19use crate::layout;
20use crate::out::diag;
21
22pub const ABANDONED: &str = "sdd: abandoned attempt";
24
25#[derive(Debug, Clone)]
27pub struct Previous {
28 pub branch: String,
29 pub seq: i64,
30 pub outcome: String,
33 pub note: String,
35}
36
37pub fn previous_attempt(
41 git: &Git,
42 inst: &Instance,
43 unit: &str,
44 below: i64,
45) -> Result<Option<Previous>, CoreError> {
46 let slug = layout::sdd_slug(inst);
47 let (events, _) = journal::read(&inst.handle())?;
48 let verified_at = events
49 .iter()
50 .filter(|e| e.event == "verified" && e.unit.as_deref() == Some(unit))
51 .filter_map(|e| e.claim_seq)
52 .max()
53 .unwrap_or(0);
54 let mut best: Option<(i64, String)> = None;
55 for branch in git
56 .branches_under(&layout::branch_prefix(&slug, unit))
57 .map_err(CoreError::from)?
58 {
59 let Some(seq) = layout::branch_seq(&branch) else {
60 continue;
61 };
62 if seq > verified_at && seq < below && best.as_ref().is_none_or(|(s, _)| seq > *s) {
63 best = Some((seq, branch));
64 }
65 }
66 let Some((seq, branch)) = best else {
67 return Ok(None);
68 };
69 let message = git.commit_message(&branch).unwrap_or_default();
70 let (subject, body) = message.split_once('\n').unwrap_or((message.as_str(), ""));
71 let (outcome, note) = match subject.strip_prefix(ABANDONED) {
72 Some(rest) => (
73 rest.rsplit_once(" — ")
74 .map(|(_, o)| o.trim().to_string())
75 .unwrap_or_default(),
76 body.trim().to_string(),
77 ),
78 None => (String::new(), String::new()),
79 };
80 Ok(Some(Previous {
81 branch,
82 seq,
83 outcome,
84 note,
85 }))
86}
87
88pub fn seed(
92 wt: &Git,
93 ws: &WriteSet,
94 claim_commit: &str,
95 prev: &Previous,
96) -> Result<Vec<String>, CoreError> {
97 let fork = wt
98 .merge_base(claim_commit, &prev.branch)
99 .map_err(CoreError::from)?;
100 let owned: Vec<String> = wt
101 .added_or_modified(&fork, &prev.branch)
102 .map_err(CoreError::from)?
103 .into_iter()
104 .filter(|p| ws.covers(p))
105 .collect();
106 wt.restore_paths(&prev.branch, &owned)
107 .map_err(CoreError::from)?;
108 Ok(owned)
109}
110
111pub fn abandon(primary: &Git, wt: &Path, unit: &str, seq: i64, outcome: &str, detail: &str) {
116 if !wt.join(".git").exists() {
117 return;
118 }
119 let git = primary.at(wt);
120 let subject = format!("{ABANDONED} {unit} (c{seq}) — {outcome}");
121 let saved = git
122 .add_all()
123 .and_then(|()| git.commit_note(&subject, &clip(detail, 60, 6000)));
124 match saved {
125 Ok(()) => {
126 let _ = primary.worktree_remove(wt);
127 }
128 Err(e) => diag(&format!(
129 "warning: could not save the attempt at {unit} (c{seq}) to its branch ({e}); its worktree is kept at {}",
130 wt.display()
131 )),
132 }
133}
134
135pub fn clip(text: &str, lines: usize, bytes: usize) -> String {
137 let all: Vec<&str> = text.lines().collect();
138 let start = all.len().saturating_sub(lines);
139 let mut out = all[start..].join("\n");
140 if out.len() > bytes {
141 let mut cut = out.len() - bytes;
142 while !out.is_char_boundary(cut) {
143 cut += 1;
144 }
145 out = out[cut..].to_string();
146 }
147 out
148}
149
150pub struct Orchestrated<'a> {
152 pub unit: &'a str,
153 pub holder: &'a str,
154 pub seq: i64,
155 pub branch: &'a str,
156 pub worktree: &'a Path,
157 pub sdd: &'a str,
159}
160
161pub fn section(
166 orchestrated: Option<&Orchestrated<'_>>,
167 prev: Option<&Previous>,
168 seeded: &[String],
169 stale_cause: Option<&str>,
170) -> String {
171 let mut items: Vec<String> = Vec::new();
172 if let Some(o) = orchestrated {
173 items.push(format!(
174 "- **Your claim is made and your working copy is ready.** The orchestrator claimed {} for holder `{}` (claim `c{}`) and created the worktree `{}` on branch `{}` — your current directory. Skip steps 1 and 2.",
175 o.unit,
176 o.holder,
177 o.seq,
178 o.worktree.display(),
179 o.branch
180 ));
181 items.push(
182 "- **Stay in that directory.** Run every command from it and write nothing outside it: the primary checkout and every other worktree are not yours."
183 .to_string(),
184 );
185 items.push(
186 "- **The lease is the orchestrator's.** Do not run `vitrify claim`, `vitrify renew` or `vitrify release`: the orchestrator renews the lease while you work, and releases it when you report `blocked` or `released`."
187 .to_string(),
188 );
189 items.push(format!(
190 "- **Name the SDD.** Every `vitrify` command you run takes `--sdd {}` — this repository may hold several SDDs, each with its own `{}`.",
191 o.sdd, o.unit
192 ));
193 }
194 if let Some(cause) = stale_cause {
195 items.push(format!(
196 "- **This unit was built and verified before, then marked Stale** ({cause}). Its earlier code is in your working copy. Take the reading set below as the current truth, bring the files this unit owns into line with it — often a small change, sometimes none — run the full unit gate, and stamp Built again."
197 ));
198 }
199 if let Some(p) = prev {
200 let how = if p.outcome.is_empty() {
201 "did not land".to_string()
202 } else {
203 format!("did not land: `{}`", p.outcome)
204 };
205 let mut item = format!(
206 "- **An earlier attempt at this unit {how}** (branch `{}`).",
207 p.branch
208 );
209 if !p.note.is_empty() {
210 item.push_str(" What was recorded:\n\n");
211 for line in p.note.lines() {
212 item.push_str(" ");
213 item.push_str(line);
214 item.push('\n');
215 }
216 }
217 items.push(item.trim_end().to_string());
218 if seeded.is_empty() {
219 if orchestrated.is_none() {
220 items.push(format!(
221 "- Its files are on that branch: `git checkout {} -- <path>` brings back one this unit owns. They are a draft written against the spec as it then stood.",
222 p.branch
223 ));
224 }
225 } else {
226 items.push(format!(
227 "- **Its files are already in your working copy**, uncommitted: {}. They were written against the spec as it then stood and did not land: treat them as a draft, check every line against the reading set below, and keep, fix or replace them as that requires.",
228 seeded
229 .iter()
230 .map(|p| format!("`{p}`"))
231 .collect::<Vec<_>>()
232 .join(", ")
233 ));
234 }
235 }
236 if items.is_empty() {
237 return String::new();
238 }
239 format!("## This session\n\n{}", items.join("\n"))
240}
241
242#[cfg(test)]
243mod tests {
244 use super::*;
245
246 #[test]
247 fn clip_keeps_the_tail() {
248 let text = (1..=100)
249 .map(|i| format!("line {i}"))
250 .collect::<Vec<_>>()
251 .join("\n");
252 let c = clip(&text, 3, 1000);
253 assert_eq!(c, "line 98\nline 99\nline 100");
254 assert_eq!(clip("αβγδ", 5, 4), "γδ");
255 }
256
257 #[test]
258 fn section_says_nothing_when_there_is_nothing_to_say() {
259 assert_eq!(section(None, None, &[], None), "");
260 }
261
262 #[test]
263 fn section_names_the_branch_the_outcome_and_the_seeded_files() {
264 let prev = Previous {
265 branch: "sdd/x/U-003/c2".into(),
266 seq: 2,
267 outcome: "rejected-gate".into(),
268 note: "failing gate: `npm test`\nexpected 3, got 4".into(),
269 };
270 let s = section(None, Some(&prev), &["src/a.ts".to_string()], None);
271 assert!(s.starts_with("## This session\n\n"));
272 assert!(s.contains("did not land: `rejected-gate`"));
273 assert!(s.contains("branch `sdd/x/U-003/c2`"));
274 assert!(s.contains(" expected 3, got 4"));
275 assert!(s.contains("already in your working copy"));
276 assert!(s.contains("`src/a.ts`"));
277 }
278}