1use std::collections::{BTreeMap, BTreeSet};
21use std::path::{Path, PathBuf};
22
23use vitrify_core::CoreError;
24use vitrify_core::cascade::{self, Anchors, Candidate, Changes, Closures, Dirty, Ownership, Why};
25use vitrify_core::graph::{self, Cycles, Node, Resolution, UnitGraph};
26use vitrify_core::journal;
27use vitrify_core::model::{self, Instance, Shape};
28use vitrify_core::trace;
29
30use crate::cmd;
31use crate::git::Git;
32
33#[derive(Debug, Clone, Default, PartialEq, Eq)]
38pub struct SpecFiles {
39 pub bundles: Vec<String>,
42 pub singles: Vec<String>,
44}
45
46impl SpecFiles {
47 pub fn of(root: &Path, sdds: &[Instance]) -> SpecFiles {
49 let mut out = SpecFiles::default();
50 for inst in sdds {
51 match inst.shape {
52 Shape::Bundle => {
53 let dir = cmd::shown(root, &inst.root);
54 out.bundles
55 .push(if dir == "." { String::new() } else { dir });
56 }
57 Shape::Single => out.singles.push(cmd::shown(root, &inst.file)),
58 }
59 }
60 out.bundles.sort();
61 out.bundles.dedup();
62 out.singles.sort();
63 out.singles.dedup();
64 out
65 }
66
67 fn is_bundle(&self, dir: &str) -> bool {
68 self.bundles
69 .binary_search_by(|b| b.as_str().cmp(dir))
70 .is_ok()
71 }
72
73 fn is_single(&self, path: &str) -> bool {
74 self.singles
75 .binary_search_by(|s| s.as_str().cmp(path))
76 .is_ok()
77 }
78}
79
80pub fn classify_changes(
87 git: &Git,
88 old: &str,
89 new: &str,
90 spec: &SpecFiles,
91) -> Result<Vec<(String, bool)>, CoreError> {
92 let both = |path: &str| -> Option<(String, String)> {
93 Some((
94 git.show_text(old, path).ok().flatten()?,
95 git.show_text(new, path).ok().flatten()?,
96 ))
97 };
98 let mut paths = git.changed_paths(old, new).map_err(CoreError::from)?;
99 paths.sort();
100 paths.dedup();
101 let mut out = Vec::with_capacity(paths.len());
102 for path in paths {
103 let (dir, name) = path.rsplit_once('/').unwrap_or(("", path.as_str()));
104 let state_only = if matches!(
105 name,
106 "journal.ndjson" | "ledger.md" | "decisions.md" | "changelog.md"
107 ) {
108 spec.is_bundle(dir)
109 } else if spec.is_single(&path) {
110 both(&path).is_some_and(|(a, b)| single_state_masked(&a) == single_state_masked(&b))
111 } else if (dir == "units" || dir.ends_with("/units"))
112 && name.starts_with("U-")
113 && name.ends_with(".md")
114 && spec.is_bundle(dir.trim_end_matches("units").trim_end_matches('/'))
115 {
116 both(&path).is_some_and(|(a, b)| {
117 trace::mask_unit_fields(Shape::Bundle, &a, "", &trace::VOLATILE)
118 == trace::mask_unit_fields(Shape::Bundle, &b, "", &trace::VOLATILE)
119 })
120 } else {
121 false
122 };
123 out.push((path, state_only));
124 }
125 Ok(out)
126}
127
128#[derive(Debug, Default)]
133pub struct DiffCache {
134 head: String,
135 full_of: BTreeMap<String, Option<String>>,
137 paths: BTreeMap<String, Vec<String>>,
139}
140
141impl DiffCache {
142 fn advance(&mut self, git: &Git, head: &str) -> Result<(), CoreError> {
145 if self.head == head {
146 return Ok(());
147 }
148 let old = std::mem::replace(&mut self.head, head.to_string());
149 if old.is_empty()
150 || self.paths.is_empty()
151 || !git.is_ancestor(&old, head).map_err(CoreError::from)?
152 {
153 self.paths.clear();
154 return Ok(());
155 }
156 let moved = git.changed_paths(&old, head).map_err(CoreError::from)?;
157 if moved.is_empty() {
158 return Ok(());
159 }
160 if moved.iter().any(|p| p.contains('\n')) {
161 self.paths.clear();
162 return Ok(());
163 }
164 let mut names: Vec<String> = moved.iter().map(|p| format!("{head}:{p}")).collect();
167 let anchors: Vec<String> = self.paths.keys().cloned().collect();
168 for a in &anchors {
169 names.extend(moved.iter().map(|p| format!("{a}:{p}")));
170 }
171 let ids = git.object_ids(&names).map_err(CoreError::from)?;
172 let at_head = &ids[..moved.len()];
173 for (k, a) in anchors.iter().enumerate() {
174 let at_anchor = &ids[(k + 1) * moved.len()..(k + 2) * moved.len()];
175 let Some(paths) = self.paths.get_mut(a) else {
176 continue;
177 };
178 let mut set: BTreeSet<String> = std::mem::take(paths).into_iter().collect();
179 for (i, p) in moved.iter().enumerate() {
180 if at_anchor[i] == at_head[i] {
181 set.remove(p);
182 } else {
183 set.insert(p.clone());
184 }
185 }
186 *paths = set.into_iter().collect();
187 }
188 Ok(())
189 }
190}
191
192pub fn substantive_changes(
195 git: &Git,
196 old: &str,
197 new: &str,
198 spec: &SpecFiles,
199) -> Result<Vec<String>, CoreError> {
200 Ok(classify_changes(git, old, new, spec)?
201 .into_iter()
202 .filter(|(_, state_only)| !state_only)
203 .map(|(path, _)| path)
204 .collect())
205}
206
207pub fn benign(git: &Git, old: &str, new: &str, spec: &SpecFiles) -> Result<bool, CoreError> {
211 if old == new {
212 return Ok(true);
213 }
214 if !git.is_ancestor(old, new).map_err(CoreError::from)? {
215 return Ok(false);
216 }
217 Ok(substantive_changes(git, old, new, spec)?.is_empty())
218}
219
220fn single_state_masked(text: &str) -> String {
224 let mut t = text.to_string();
225 let ids: Vec<String> = model::split_h3_regions(&t, "Work Units")
226 .into_iter()
227 .map(|(id, _)| id)
228 .collect();
229 for id in ids {
230 if let Some(masked) = trace::mask_unit_fields(Shape::Single, &t, &id, &trace::VOLATILE) {
231 t = masked;
232 }
233 }
234 for heading in [
235 "Journal",
236 "State Ledger",
237 "Decisions & Open Questions",
238 "Changelog",
239 ] {
240 if let Some((s, e)) = model::section_span(&t, heading) {
241 t = format!("{}{}", &t[..s], &t[e..]);
242 }
243 }
244 t
245}
246
247#[derive(Debug, Clone)]
251pub struct SddAt {
252 pub slug: String,
254 pub root: String,
257 pub inst: Instance,
258 pub anchors: Anchors,
260}
261
262#[derive(Debug, Clone)]
264pub struct Snapshot {
265 pub checkout: PathBuf,
267 pub head: String,
269 pub sdds: Vec<SddAt>,
271 pub graph: UnitGraph,
272 pub resolved: Result<Resolution, Cycles>,
274 pub ownership: Ownership,
275 pub spec: SpecFiles,
276}
277
278#[derive(Debug, Clone, Copy, PartialEq, Eq)]
280pub enum Mode {
281 Changes,
283 Everything,
286}
287
288#[derive(Debug, Clone, PartialEq, Eq)]
290pub struct SuiteState {
291 pub slug: String,
292 pub anchor: Option<String>,
295 pub dirty: Option<Why>,
297}
298
299#[derive(Debug, Clone, PartialEq, Eq)]
301pub struct DirtySet {
302 pub head: String,
304 pub units: Vec<Dirty>,
306 pub suites: Vec<SuiteState>,
308 pub unresolved: Vec<String>,
310}
311
312impl DirtySet {
313 pub fn of_sdd<'a>(&'a self, slug: &'a str) -> impl Iterator<Item = &'a Dirty> + 'a {
315 self.units.iter().filter(move |d| d.node.slug == slug)
316 }
317
318 pub fn is_dirty(&self, node: &Node) -> bool {
320 self.units.binary_search_by(|d| d.node.cmp(node)).is_ok()
321 }
322
323 pub fn suite(&self, slug: &str) -> Option<&SuiteState> {
325 self.suites.iter().find(|s| s.slug == slug)
326 }
327}
328
329#[derive(Debug, Clone, PartialEq, Eq)]
331pub enum Cascade {
332 Resolved(DirtySet),
333 Cycles(Cycles),
336}
337
338pub fn describe(why: &Why) -> String {
342 match why {
343 Why::NoDiff(anchor) => {
344 format!("anchor {anchor} cannot be resolved (rewritten history, or a shallow clone)")
345 }
346 other => other.describe(),
347 }
348}
349
350impl Snapshot {
351 pub fn load(git: &Git, checkout: &Path, head: &str) -> Result<Snapshot, CoreError> {
356 let head = git
357 .resolve_commit(head)
358 .map_err(CoreError::from)?
359 .ok_or_else(|| CoreError::refusal(1, format!("error: {head} names no commit")))?;
360 let mut sdds: Vec<SddAt> = Vec::new();
361 for handle in cmd::discover(checkout) {
362 let inst = Instance::load(handle)?;
363 let (events, _) = journal::read(&inst.handle())?;
364 sdds.push(SddAt {
365 slug: graph::slug_of(&inst).to_string(),
366 root: cmd::shown(checkout, &inst.root),
367 anchors: Anchors::from_events(&events),
368 inst,
369 });
370 }
371 sdds.sort_by(|a, b| (&a.slug, &a.root).cmp(&(&b.slug, &b.root)));
372 let instances: Vec<Instance> = sdds.iter().map(|s| s.inst.clone()).collect();
373 let graph = UnitGraph::build(&instances)?;
374 let resolved = graph.resolve();
375 let ownership =
376 Ownership::build(checkout, sdds.iter().map(|s| (s.slug.as_str(), &s.inst)))?;
377 let spec = SpecFiles::of(checkout, &instances);
378 Ok(Snapshot {
379 checkout: checkout.to_path_buf(),
380 head,
381 sdds,
382 graph,
383 resolved,
384 ownership,
385 spec,
386 })
387 }
388
389 pub fn load_resolvable(
396 git: &Git,
397 checkout: &Path,
398 head: &str,
399 ) -> Result<(Snapshot, Option<Cycles>), CoreError> {
400 let full = git
401 .resolve_commit(head)
402 .map_err(CoreError::from)?
403 .ok_or_else(|| CoreError::refusal(1, format!("error: {head} names no commit")))?;
404 let mut all: Vec<SddAt> = Vec::new();
405 for handle in cmd::discover(checkout) {
406 let Ok(inst) = Instance::load(handle) else {
407 continue;
408 };
409 let (events, _) = journal::read(&inst.handle()).unwrap_or_default();
410 all.push(SddAt {
411 slug: graph::slug_of(&inst).to_string(),
412 root: cmd::shown(checkout, &inst.root),
413 anchors: Anchors::from_events(&events),
414 inst,
415 });
416 }
417 all.sort_by(|a, b| (&a.slug, &a.root).cmp(&(&b.slug, &b.root)));
418 let every: Vec<Instance> = all.iter().map(|s| s.inst.clone()).collect();
419 let ownership = Ownership::build(checkout, all.iter().map(|s| (s.slug.as_str(), &s.inst)))?;
420 let spec = SpecFiles::of(checkout, &every);
421 let mut graph = UnitGraph::build(&every)?;
422 let mut resolved = graph.resolve();
423 let mut cycles = None;
424 if let Err(c) = &resolved {
425 let on_cycle: BTreeSet<&str> =
426 c.cycles.iter().flatten().map(|n| n.slug.as_str()).collect();
427 let kept: Vec<SddAt> = all
428 .iter()
429 .filter(|s| !on_cycle.contains(s.slug.as_str()))
430 .cloned()
431 .collect();
432 cycles = Some(c.clone());
433 let instances: Vec<Instance> = kept.iter().map(|s| s.inst.clone()).collect();
434 graph = UnitGraph::build(&instances)?;
435 resolved = graph.resolve();
436 all = kept;
437 }
438 Ok((
439 Snapshot {
440 checkout: checkout.to_path_buf(),
441 head: full,
442 sdds: all,
443 graph,
444 resolved,
445 ownership,
446 spec,
447 },
448 cycles,
449 ))
450 }
451
452 pub fn sdd(&self, slug: &str) -> Option<&SddAt> {
454 self.sdds.iter().find(|s| s.slug == slug)
455 }
456
457 pub fn candidates(&self) -> Vec<Candidate> {
459 let mut out: Vec<Candidate> = self
460 .sdds
461 .iter()
462 .flat_map(|s| {
463 s.inst
464 .units
465 .iter()
466 .filter(|u| u.meta.get_str_or("status", "Draft") == "Verified")
467 .map(|u| Candidate {
468 node: Node::new(&s.slug, &u.unit),
469 anchor: s.anchors.unit(&u.unit).map(str::to_string),
470 })
471 })
472 .collect();
473 out.sort_by(|a, b| a.node.cmp(&b.node));
474 out
475 }
476
477 pub fn dirty(&self, git: &Git, mode: Mode) -> Result<Cascade, CoreError> {
482 self.dirty_with(git, mode, &mut DiffCache::default())
483 }
484
485 pub fn dirty_with(
489 &self,
490 git: &Git,
491 mode: Mode,
492 cache: &mut DiffCache,
493 ) -> Result<Cascade, CoreError> {
494 let resolution = match &self.resolved {
495 Ok(r) => r,
496 Err(cycles) => return Ok(Cascade::Cycles(cycles.clone())),
497 };
498 let candidates = self.candidates();
499 if mode == Mode::Everything {
500 return Ok(Cascade::Resolved(DirtySet {
501 head: self.head.clone(),
502 units: cascade::dirty_everything(&candidates),
503 suites: self
504 .sdds
505 .iter()
506 .map(|s| SuiteState {
507 slug: s.slug.clone(),
508 anchor: s.anchors.suite.clone(),
509 dirty: Some(Why::Everything),
510 })
511 .collect(),
512 unresolved: Vec::new(),
513 }));
514 }
515 let closures: Closures = self
516 .graph
517 .nodes()
518 .iter()
519 .map(|n| {
520 let deps: BTreeSet<Node> = resolution.closure(n).into_iter().cloned().collect();
521 (n.clone(), deps)
522 })
523 .collect();
524
525 let mut recorded: BTreeSet<&str> = candidates
527 .iter()
528 .filter_map(|c| c.anchor.as_deref())
529 .collect();
530 recorded.extend(self.sdds.iter().filter_map(|s| s.anchors.suite.as_deref()));
531 let mut full_of: BTreeMap<&str, String> = BTreeMap::new();
532 let mut unresolved: Vec<String> = Vec::new();
533 let unknown: Vec<&str> = recorded
534 .iter()
535 .copied()
536 .filter(|a| !cache.full_of.contains_key(*a))
537 .collect();
538 let names: Vec<String> = unknown.iter().map(|a| format!("{a}^{{commit}}")).collect();
539 for (anchor, full) in unknown
540 .iter()
541 .zip(git.object_ids(&names).map_err(CoreError::from)?)
542 {
543 cache.full_of.insert(anchor.to_string(), full);
544 }
545 for anchor in recorded {
546 match cache.full_of.get(anchor).cloned().flatten() {
547 Some(full) => {
548 full_of.insert(anchor, full);
549 }
550 None => unresolved.push(anchor.to_string()),
551 }
552 }
553 cache.advance(git, &self.head)?;
554 let mut diffs: BTreeMap<&str, Vec<String>> = BTreeMap::new();
560 for full in full_of.values() {
561 if !diffs.contains_key(full.as_str()) {
562 let paths = match cache.paths.get(full.as_str()) {
563 Some(paths) => paths.clone(),
564 None => {
565 let mut paths = git
566 .changed_paths(full, &self.head)
567 .map_err(CoreError::from)?;
568 paths.sort();
569 paths.dedup();
570 cache.paths.insert(full.clone(), paths.clone());
571 paths
572 }
573 };
574 diffs.insert(full.as_str(), paths);
575 }
576 }
577 let named: BTreeSet<&String> = full_of.values().collect();
579 cache.paths.retain(|full, _| named.contains(full));
580 let changes: Changes = full_of
581 .iter()
582 .map(|(anchor, full)| {
583 let paths = diffs.get(full.as_str()).cloned().unwrap_or_default();
584 (anchor.to_string(), paths)
585 })
586 .collect();
587
588 let units = cascade::dirty_set(&candidates, &changes, &closures, &self.ownership);
589 let suites = self
590 .sdds
591 .iter()
592 .map(|s| {
593 let nodes: Vec<Node> = s
594 .inst
595 .units
596 .iter()
597 .map(|u| Node::new(&s.slug, &u.unit))
598 .collect();
599 let anchor = s.anchors.suite.as_deref();
600 let changed = anchor.and_then(|a| changes.get(a)).map(Vec::as_slice);
601 SuiteState {
602 slug: s.slug.clone(),
603 anchor: s.anchors.suite.clone(),
604 dirty: cascade::suite_dirty(
605 &s.slug,
606 &nodes,
607 anchor,
608 changed,
609 &closures,
610 &self.ownership,
611 ),
612 }
613 })
614 .collect();
615 Ok(Cascade::Resolved(DirtySet {
616 head: self.head.clone(),
617 units,
618 suites,
619 unresolved,
620 }))
621 }
622}