1use std::collections::BTreeSet;
9use std::path::Path;
10
11use vitrify_core::CoreError;
12use vitrify_core::cascade::{Owner, Why};
13use vitrify_core::graph::{self, Node, UnitGraph, render_path, slug_of};
14use vitrify_core::model::Instance;
15
16use crate::out::J;
17
18#[derive(Debug, Clone, PartialEq, Eq)]
23pub struct Refused {
24 pub code: u8,
26 pub failures: Vec<String>,
27}
28
29impl Refused {
30 fn from_error(e: CoreError) -> Refused {
31 let message = e.to_string();
32 Refused {
33 code: e.exit_code(),
34 failures: vec![
35 message
36 .strip_prefix("error: ")
37 .unwrap_or(&message)
38 .to_string(),
39 ],
40 }
41 }
42}
43
44fn fixed(cause: &str, fix: &str) -> String {
45 format!("{cause} → {fix}")
46}
47
48pub fn preflight(sdds: &[Instance]) -> Result<UnitGraph, Refused> {
54 let old = graph::pins_on_2_0(sdds).map_err(Refused::from_error)?;
55 if !old.is_empty() {
56 let failures = old
57 .iter()
58 .map(|inst| {
59 fixed(
60 &format!(
61 "SDD {} ({}) is at schema 2.0 and its units consume pins — under 2.0 nothing says which pins a unit needs built first",
62 slug_of(inst),
63 inst.file.display()
64 ),
65 "migrate it to schema 2.1 and list the pins its units need in depends_on",
66 )
67 })
68 .collect();
69 return Err(Refused { code: 4, failures });
70 }
71
72 let mut failures: Vec<String> = Vec::new();
73 for inst in sdds {
74 if slug_of(inst).is_empty() {
75 failures.push(fixed(
76 &format!("SDD {} has no `sdd:` slug", inst.file.display()),
77 "set `sdd: <slug>` in its front matter",
78 ));
79 }
80 }
81 let graph = UnitGraph::build(sdds).map_err(Refused::from_error)?;
82 for clash in graph.clashes() {
83 let files: Vec<String> = clash
84 .files
85 .iter()
86 .map(|f| f.display().to_string())
87 .collect();
88 failures.push(fixed(
89 &format!(
90 "several SDDs have the slug `{}`: {}",
91 clash.slug,
92 files.join(", ")
93 ),
94 &format!(
95 "give each SDD with the slug `{}` a slug of its own",
96 clash.slug
97 ),
98 ));
99 }
100 for p in graph.problems() {
101 failures.push(fixed(
102 &format!("[{}] {} {}: {}", p.check(), p.slug, p.unit, p.cause()),
103 &p.remediation(),
104 ));
105 }
106 if let Err(cycles) = graph.resolve() {
107 for path in &cycles.cycles {
108 failures.push(fixed(
109 &format!("[L12] dependency cycle: {}", render_path(path)),
110 "break the cycle: remove one depends_on entry on that path",
111 ));
112 }
113 if !cycles.waiting.is_empty() {
114 let names: Vec<String> = cycles.waiting.iter().map(Node::to_string).collect();
115 failures.push(fixed(
116 &format!(
117 "{} {} behind a cycle: {}",
118 cycles.waiting.len(),
119 plural(cycles.waiting.len(), "unit waits", "units wait"),
120 names.join(", ")
121 ),
122 "waiting units build once the cycle is broken",
123 ));
124 }
125 }
126 if failures.is_empty() {
127 Ok(graph)
128 } else {
129 Err(Refused { code: 2, failures })
130 }
131}
132
133#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
137pub enum LaneState {
138 Idle,
140 Build,
142 Recheck,
144 UpToDate,
146 Complete,
148 Blocked,
150}
151
152impl LaneState {
153 pub fn label(self) -> &'static str {
155 match self {
156 LaneState::Idle => "idle",
157 LaneState::Build => "build",
158 LaneState::Recheck => "recheck",
159 LaneState::UpToDate => "up to date",
160 LaneState::Complete => "complete",
161 LaneState::Blocked => "blocked",
162 }
163 }
164
165 pub fn title(self) -> &'static str {
167 match self {
168 LaneState::Idle => "Idle",
169 LaneState::Build => "Build",
170 LaneState::Recheck => "Recheck",
171 LaneState::UpToDate => "Up to date",
172 LaneState::Complete => "Complete",
173 LaneState::Blocked => "Blocked",
174 }
175 }
176
177 fn count_phrase(self, n: usize) -> String {
179 match self {
180 LaneState::Idle => format!("{n} idle"),
181 LaneState::Build => format!("{n} to build"),
182 LaneState::Recheck => format!("{n} to re-check"),
183 LaneState::UpToDate => format!("{n} up to date"),
184 LaneState::Complete => format!("{n} complete"),
185 LaneState::Blocked => format!("{n} blocked"),
186 }
187 }
188}
189
190#[derive(Debug, Clone, PartialEq, Eq)]
193pub struct Lane {
194 pub slug: String,
195 pub root: String,
196 pub records: String,
198 pub state: LaneState,
199 pub units: usize,
201 pub verified: usize,
202 pub regenerate: usize,
203 pub adopt: usize,
204 pub recheck: usize,
205}
206
207#[derive(Debug, Clone, PartialEq, Eq)]
209pub struct Adopt {
210 pub node: Node,
211 pub attempt: i64,
212}
213
214#[derive(Debug, Clone, PartialEq, Eq)]
216pub struct Recheck {
217 pub node: Node,
218 pub why: Why,
219}
220
221impl Recheck {
222 pub fn changed_units(&self) -> Vec<&Node> {
224 let Why::Paths(reasons) = &self.why else {
225 return Vec::new();
226 };
227 let set: BTreeSet<&Node> = reasons
228 .iter()
229 .filter_map(|r| match &r.owner {
230 Owner::Unit(n) | Owner::Test { unit: Some(n), .. } => Some(n),
231 _ => None,
232 })
233 .collect();
234 set.into_iter().collect()
235 }
236}
237
238#[derive(Debug, Clone, Copy, PartialEq, Eq)]
240pub struct Capacity {
241 pub workers: usize,
242 pub gate_jobs: usize,
243 pub lanes: usize,
245}
246
247#[derive(Debug, Clone, PartialEq, Eq)]
249pub struct Plan {
250 pub job_id: String,
251 pub lanes: Vec<Lane>,
253 pub regenerate: Vec<Node>,
255 pub adopt: Vec<Adopt>,
257 pub recheck: Vec<Recheck>,
259 pub critical_path: Vec<Node>,
260 pub capacity: Capacity,
261}
262
263impl Plan {
264 pub fn sorted(mut self) -> Plan {
267 self.lanes.sort_by(|a, b| a.slug.cmp(&b.slug));
268 self.regenerate.sort();
269 self.adopt.sort_by(|a, b| a.node.cmp(&b.node));
270 self.recheck.sort_by(|a, b| a.node.cmp(&b.node));
271 self
272 }
273
274 pub fn changed_units(&self) -> Vec<&Node> {
276 let set: BTreeSet<&Node> = self
277 .recheck
278 .iter()
279 .flat_map(|r| r.changed_units())
280 .collect();
281 set.into_iter().collect()
282 }
283}
284
285fn plural<'a>(n: usize, one: &'a str, many: &'a str) -> &'a str {
288 if n == 1 { one } else { many }
289}
290
291fn critical_line(path: &[Node]) -> String {
292 if path.is_empty() {
293 "Critical path: none".to_string()
294 } else {
295 format!(
296 "Critical path: {} ({} {})",
297 render_path(path),
298 path.len(),
299 plural(path.len(), "unit", "units")
300 )
301 }
302}
303
304fn capacity_line(c: &Capacity) -> String {
305 let lanes = if c.lanes == 0 {
306 "unlimited".to_string()
307 } else {
308 c.lanes.to_string()
309 };
310 format!(
311 "Capacity: workers {} · gate jobs {} · lanes {lanes}",
312 c.workers, c.gate_jobs
313 )
314}
315
316fn changed_phrase(changed: &[&Node]) -> Option<String> {
319 if changed.is_empty() {
320 return None;
321 }
322 let shown: Vec<String> = changed.iter().take(3).map(|n| n.to_string()).collect();
323 let more = changed.len().saturating_sub(3);
324 Some(if more > 0 {
325 format!("{} and {more} more changed", shown.join(", "))
326 } else {
327 format!("{} changed", shown.join(", "))
328 })
329}
330
331pub fn header(plan: &Plan, watch: bool) -> Vec<String> {
335 let mut counts: Vec<String> = Vec::new();
336 for state in [
337 LaneState::Build,
338 LaneState::Recheck,
339 LaneState::UpToDate,
340 LaneState::Idle,
341 LaneState::Blocked,
342 LaneState::Complete,
343 ] {
344 let n = plan.lanes.iter().filter(|l| l.state == state).count();
345 if n > 0 {
346 counts.push(state.count_phrase(n));
347 }
348 }
349 let n = plan.lanes.len();
350 let mut lines = vec![format!(
351 "Project build job — {n} {}: {} [{}]",
352 plural(n, "SDD", "SDDs"),
353 counts.join(" · "),
354 plan.job_id
355 )];
356 let mut summary = format!(
357 "Plan: regenerate {} {} · adopt {} {} · re-check {} {}",
358 plan.regenerate.len(),
359 plural(plan.regenerate.len(), "unit", "units"),
360 plan.adopt.len(),
361 plural(plan.adopt.len(), "built attempt", "built attempts"),
362 plan.recheck.len(),
363 plural(plan.recheck.len(), "unit", "units"),
364 );
365 if let Some(why) = changed_phrase(&plan.changed_units()) {
366 summary.push_str(&format!(" ({why})"));
367 }
368 lines.push(summary);
369 lines.push(critical_line(&plan.critical_path));
370 lines.push(capacity_line(&plan.capacity));
371 if watch {
372 lines.push(format!(
373 "Watch: vitrify run status --job {} --follow",
374 plan.job_id
375 ));
376 }
377 lines
378}
379
380pub fn dry_run(plan: &Plan) -> Vec<String> {
384 let mut lines = header(plan, false);
385 lines.push("Lanes:".to_string());
386 let slug_w = plan.lanes.iter().map(|l| l.slug.len()).max().unwrap_or(0);
387 let state_w = plan
388 .lanes
389 .iter()
390 .map(|l| l.state.label().len())
391 .max()
392 .unwrap_or(0);
393 for l in &plan.lanes {
394 lines.push(format!(
395 " {:slug_w$} {:state_w$} {}/{} Verified · regenerate {} · adopt {} · re-check {} ({})",
396 l.slug,
397 l.state.label(),
398 l.verified,
399 l.units,
400 l.regenerate,
401 l.adopt,
402 l.recheck,
403 l.root
404 ));
405 }
406 lines.push(format!("Regenerate ({}):", plan.regenerate.len()));
407 for n in &plan.regenerate {
408 lines.push(format!(" {n}"));
409 }
410 lines.push(format!("Adopt ({}):", plan.adopt.len()));
411 for a in &plan.adopt {
412 lines.push(format!(" {} built attempt c{}", a.node, a.attempt));
413 }
414 lines.push(format!("Re-check ({}):", plan.recheck.len()));
415 for r in &plan.recheck {
416 lines.push(format!(" {} {}", r.node, r.why.describe()));
417 if let Some(why) = changed_phrase(&r.changed_units()) {
418 lines.push(format!(" {why}"));
419 }
420 }
421 lines
422}
423
424pub fn event_line(slug: &str, message: &str) -> String {
427 format!("[{slug}] {message}")
428}
429
430pub fn adopted_line(slug: &str, unit: &str, attempt: i64) -> String {
432 event_line(
433 slug,
434 &format!("{unit} adopted (built attempt c{attempt}) → gate"),
435 )
436}
437
438#[derive(Debug, Clone, PartialEq, Eq)]
440pub enum LaneOutcome {
441 Complete {
442 verified: usize,
443 total: usize,
444 built: usize,
446 rechecked: usize,
448 changed: Vec<String>,
450 suite: Option<bool>,
453 model_calls: usize,
455 },
456 Blocked {
458 detail: String,
459 },
460 UpToDate {
461 since: String,
462 },
463}
464
465#[derive(Debug, Clone, PartialEq, Eq)]
467pub struct LaneReport {
468 pub slug: String,
469 pub outcome: LaneOutcome,
470}
471
472impl LaneReport {
473 pub fn state(&self) -> LaneState {
474 match self.outcome {
475 LaneOutcome::Complete { .. } => LaneState::Complete,
476 LaneOutcome::Blocked { .. } => LaneState::Blocked,
477 LaneOutcome::UpToDate { .. } => LaneState::UpToDate,
478 }
479 }
480
481 fn detail(&self) -> String {
482 match &self.outcome {
483 LaneOutcome::Complete {
484 verified,
485 total,
486 built,
487 rechecked,
488 changed,
489 suite,
490 model_calls,
491 } => {
492 let mut parts = vec![format!("{verified}/{total} Verified")];
493 if *built > 0 {
494 parts.push(format!("built {built}"));
495 }
496 if *rechecked > 0 {
497 parts.push(if changed.is_empty() {
498 format!("re-checked {rechecked}")
499 } else {
500 format!("re-checked {rechecked} ({} changed)", changed.join(", "))
501 });
502 }
503 if let Some(ok) = suite {
504 parts.push(format!(
505 "§5 Test {}",
506 if *ok { "passing" } else { "failing" }
507 ));
508 }
509 let mut text = parts.join(" · ");
510 if *model_calls == 0 && *rechecked > 0 {
511 text.push_str(", no model calls");
512 }
513 text
514 }
515 LaneOutcome::Blocked { detail } => detail.clone(),
516 LaneOutcome::UpToDate { since } => format!("nothing changed since {since}"),
517 }
518 }
519}
520
521pub fn report(lanes: &[LaneReport]) -> Vec<String> {
524 let blocked = lanes.iter().any(|l| l.state() == LaneState::Blocked);
525 let mut lines = vec![if blocked { "Blocked." } else { "Complete." }.to_string()];
526 let mut sorted: Vec<&LaneReport> = lanes.iter().collect();
527 sorted.sort_by(|a, b| a.slug.cmp(&b.slug));
528 let slug_w = sorted
529 .iter()
530 .map(|l| l.slug.len())
531 .max()
532 .unwrap_or(0)
533 .max(8);
534 for l in sorted {
535 lines.push(format!(
536 " {:slug_w$} {:12} {}",
537 l.slug,
538 l.state().title(),
539 l.detail()
540 ));
541 }
542 lines
543}
544
545#[derive(Debug, Clone, PartialEq, Eq)]
550pub struct ProjectRecord {
551 pub started_at: String,
552 pub ended_at: Option<String>,
554 pub plan: Plan,
556 pub critical_path_ran: Vec<Node>,
558}
559
560fn node_pairs(n: &Node) -> Vec<(String, J)> {
561 vec![
562 ("sdd".into(), J::s(n.slug.clone())),
563 ("unit".into(), J::s(n.unit.clone())),
564 ]
565}
566
567fn node_json(n: &Node) -> J {
568 J::Obj(node_pairs(n))
569}
570
571fn int(n: usize) -> J {
572 J::Int(n as i64)
573}
574
575impl ProjectRecord {
576 pub fn to_json(&self) -> J {
577 let p = &self.plan;
578 let lanes = p
579 .lanes
580 .iter()
581 .map(|l| {
582 J::Obj(vec![
583 ("slug".into(), J::s(l.slug.clone())),
584 ("root".into(), J::s(l.root.clone())),
585 ("records".into(), J::s(l.records.clone())),
586 ("state".into(), J::s(l.state.label())),
587 ("units".into(), int(l.units)),
588 ("verified".into(), int(l.verified)),
589 ("regenerate".into(), int(l.regenerate)),
590 ("adopt".into(), int(l.adopt)),
591 ("recheck".into(), int(l.recheck)),
592 ])
593 })
594 .collect();
595 let adopt = p
596 .adopt
597 .iter()
598 .map(|a| {
599 let mut pairs = node_pairs(&a.node);
600 pairs.push(("attempt".into(), J::Int(a.attempt)));
601 J::Obj(pairs)
602 })
603 .collect();
604 let recheck = p
605 .recheck
606 .iter()
607 .map(|r| {
608 let mut pairs = node_pairs(&r.node);
609 pairs.push(("why".into(), J::s(r.why.describe())));
610 pairs.push((
611 "changed_units".into(),
612 J::Arr(r.changed_units().into_iter().map(node_json).collect()),
613 ));
614 J::Obj(pairs)
615 })
616 .collect();
617 J::Obj(vec![
618 ("job_id".into(), J::s(p.job_id.clone())),
619 ("started_at".into(), J::s(self.started_at.clone())),
620 ("ended_at".into(), J::opt_str(self.ended_at.clone())),
621 (
622 "capacity".into(),
623 J::Obj(vec![
624 ("workers".into(), int(p.capacity.workers)),
625 ("gate_jobs".into(), int(p.capacity.gate_jobs)),
626 ("lanes".into(), int(p.capacity.lanes)),
627 ]),
628 ),
629 ("lanes".into(), J::Arr(lanes)),
630 (
631 "regenerate".into(),
632 J::Arr(p.regenerate.iter().map(node_json).collect()),
633 ),
634 ("adopt".into(), J::Arr(adopt)),
635 ("recheck".into(), J::Arr(recheck)),
636 (
637 "critical_path".into(),
638 J::Arr(p.critical_path.iter().map(node_json).collect()),
639 ),
640 (
641 "critical_path_ran".into(),
642 J::Arr(self.critical_path_ran.iter().map(node_json).collect()),
643 ),
644 ])
645 }
646
647 pub fn write(&self, logs_dir: &Path) -> std::io::Result<()> {
649 std::fs::create_dir_all(logs_dir)?;
650 let mut text = self.to_json().dumps_indent2();
651 text.push('\n');
652 std::fs::write(logs_dir.join("project.json"), text)
653 }
654}
655
656pub fn select_lanes(graph: &UnitGraph, slug: &str, upstream: bool) -> Option<Vec<String>> {
662 if !graph.slugs().iter().any(|s| s == slug) {
663 return None;
664 }
665 let mut out: BTreeSet<String> = BTreeSet::new();
666 out.insert(slug.to_string());
667 if upstream {
668 out.extend(graph.upstream(slug));
669 }
670 Some(out.into_iter().collect())
671}
672
673pub fn outside_blocker(
681 graph: &UnitGraph,
682 selected: &[String],
683 node: &Node,
684 status: &dyn Fn(&Node) -> Option<String>,
685) -> Option<String> {
686 let outside: Vec<&Node> = graph
687 .dependencies(node)
688 .into_iter()
689 .filter(|d| !selected.contains(&d.slug))
690 .filter(|d| !matches!(status(d).as_deref(), Some("Built" | "Verified")))
691 .collect();
692 if outside.is_empty() {
693 return None;
694 }
695 let units: Vec<String> = outside.iter().map(|n| n.to_string()).collect();
696 let sdds: BTreeSet<&str> = outside.iter().map(|n| n.slug.as_str()).collect();
697 let one = sdds.len() == 1;
698 let sdds: Vec<&str> = sdds.into_iter().collect();
699 Some(format!(
700 "{} waits on {}, outside this run (SDD{} {} not selected; --upstream builds {})",
701 node.unit,
702 join_and(&units),
703 if one { "" } else { "s" },
704 sdds.join(", "),
705 if one { "it" } else { "them" },
706 ))
707}
708
709fn join_and(items: &[String]) -> String {
710 match items {
711 [] => String::new(),
712 [one] => one.clone(),
713 [init @ .., last] => format!("{} and {last}", init.join(", ")),
714 }
715}
716
717#[cfg(test)]
718mod tests {
719 use super::*;
720 use vitrify_core::cascade::Reason;
721 use vitrify_core::model;
722
723 fn n(slug: &str, unit: &str) -> Node {
724 Node::new(slug, unit)
725 }
726
727 fn lane(slug: &str, state: LaneState) -> Lane {
728 Lane {
729 slug: slug.into(),
730 root: format!("specs/{slug}"),
731 records: format!(".vitrify/logs/run-x/{slug}/"),
732 state,
733 units: 12,
734 verified: 8,
735 regenerate: 2,
736 adopt: 1,
737 recheck: 0,
738 }
739 }
740
741 fn sample_plan() -> Plan {
742 Plan {
743 job_id: "run-20261121T101500Z-p4242".into(),
744 lanes: vec![
745 lane("web", LaneState::Idle),
746 lane("api", LaneState::Build),
747 lane("core", LaneState::Build),
748 lane("cli", LaneState::Recheck),
749 lane("docs", LaneState::UpToDate),
750 ],
751 regenerate: vec![n("core", "U-003"), n("api", "U-004")],
752 adopt: vec![
753 Adopt {
754 node: n("core", "U-002"),
755 attempt: 3,
756 },
757 Adopt {
758 node: n("api", "U-002"),
759 attempt: 1,
760 },
761 ],
762 recheck: vec![
763 Recheck {
764 node: n("cli", "U-002"),
765 why: Why::Paths(vec![Reason {
766 path: "core/src/lib.rs".into(),
767 owner: Owner::Unit(n("core", "U-002")),
768 }]),
769 },
770 Recheck {
771 node: n("cli", "U-001"),
772 why: Why::NoAnchor,
773 },
774 ],
775 critical_path: vec![
776 n("core", "U-001"),
777 n("core", "U-002"),
778 n("api", "U-002"),
779 n("api", "U-003"),
780 ],
781 capacity: Capacity {
782 workers: 8,
783 gate_jobs: 10,
784 lanes: 0,
785 },
786 }
787 .sorted()
788 }
789
790 #[test]
791 fn header_matches_the_documented_shape() {
792 let lines = header(&sample_plan(), true);
793 assert_eq!(
794 lines.join("\n"),
795 "Project build job — 5 SDDs: 2 to build · 1 to re-check · 1 up to date · 1 idle [run-20261121T101500Z-p4242]\n\
796 Plan: regenerate 2 units · adopt 2 built attempts · re-check 2 units (core U-002 changed)\n\
797 Critical path: core U-001 → core U-002 → api U-002 → api U-003 (4 units)\n\
798 Capacity: workers 8 · gate jobs 10 · lanes unlimited\n\
799 Watch: vitrify run status --job run-20261121T101500Z-p4242 --follow"
800 );
801 }
802
803 #[test]
804 fn header_singulars_and_lane_cap() {
805 let mut plan = sample_plan();
806 plan.lanes.truncate(1);
807 plan.regenerate.truncate(1);
808 plan.adopt.truncate(1);
809 plan.recheck.clear();
810 plan.critical_path.truncate(1);
811 plan.capacity.lanes = 3;
812 let lines = header(&plan, false);
813 assert_eq!(
814 lines.join("\n"),
815 "Project build job — 1 SDD: 1 to build [run-20261121T101500Z-p4242]\n\
816 Plan: regenerate 1 unit · adopt 1 built attempt · re-check 0 units\n\
817 Critical path: core U-001 (1 unit)\n\
818 Capacity: workers 8 · gate jobs 10 · lanes 3"
819 );
820 }
821
822 #[test]
823 fn dry_run_lists_what_regenerates_is_adopted_and_rechecked() {
824 let text = dry_run(&sample_plan()).join("\n");
825 assert_eq!(
826 text,
827 "Project build job — 5 SDDs: 2 to build · 1 to re-check · 1 up to date · 1 idle [run-20261121T101500Z-p4242]\n\
828 Plan: regenerate 2 units · adopt 2 built attempts · re-check 2 units (core U-002 changed)\n\
829 Critical path: core U-001 → core U-002 → api U-002 → api U-003 (4 units)\n\
830 Capacity: workers 8 · gate jobs 10 · lanes unlimited\n\
831 Lanes:\n\
832 \x20 api build 8/12 Verified · regenerate 2 · adopt 1 · re-check 0 (specs/api)\n\
833 \x20 cli recheck 8/12 Verified · regenerate 2 · adopt 1 · re-check 0 (specs/cli)\n\
834 \x20 core build 8/12 Verified · regenerate 2 · adopt 1 · re-check 0 (specs/core)\n\
835 \x20 docs up to date 8/12 Verified · regenerate 2 · adopt 1 · re-check 0 (specs/docs)\n\
836 \x20 web idle 8/12 Verified · regenerate 2 · adopt 1 · re-check 0 (specs/web)\n\
837 Regenerate (2):\n\
838 \x20 api U-004\n\
839 \x20 core U-003\n\
840 Adopt (2):\n\
841 \x20 api U-002 built attempt c1\n\
842 \x20 core U-002 built attempt c3\n\
843 Re-check (2):\n\
844 \x20 cli U-001 no recorded check\n\
845 \x20 cli U-002 core/src/lib.rs (unit core U-002)\n\
846 \x20 core U-002 changed"
847 );
848 }
849
850 #[test]
851 fn many_changed_units_are_abbreviated() {
852 let nodes: Vec<Node> = (1..=5).map(|i| n("core", &format!("U-00{i}"))).collect();
853 let refs: Vec<&Node> = nodes.iter().collect();
854 assert_eq!(
855 changed_phrase(&refs).unwrap(),
856 "core U-001, core U-002, core U-003 and 2 more changed"
857 );
858 assert_eq!(changed_phrase(&[]), None);
859 }
860
861 #[test]
862 fn event_lines_carry_the_lane() {
863 assert_eq!(
864 adopted_line("api", "U-002", 3),
865 "[api] U-002 adopted (built attempt c3) → gate"
866 );
867 assert_eq!(
868 event_line("core", "U-001 verified"),
869 "[core] U-001 verified"
870 );
871 }
872
873 fn sample_report() -> Vec<LaneReport> {
874 let r = |slug: &str, outcome| LaneReport {
875 slug: slug.into(),
876 outcome,
877 };
878 vec![
879 r(
880 "docs",
881 LaneOutcome::UpToDate {
882 since: "9f3c2e1".into(),
883 },
884 ),
885 r(
886 "web",
887 LaneOutcome::Blocked {
888 detail: "U-004 waits on api U-007 (rotten)".into(),
889 },
890 ),
891 r(
892 "core",
893 LaneOutcome::Complete {
894 verified: 12,
895 total: 12,
896 built: 3,
897 rechecked: 0,
898 changed: vec![],
899 suite: Some(true),
900 model_calls: 5,
901 },
902 ),
903 r(
904 "api",
905 LaneOutcome::Blocked {
906 detail: "U-007 rotten: row 2 broke at a1b2c3d (core U-004 integrated) — culprit found".into(),
907 },
908 ),
909 r(
910 "cli",
911 LaneOutcome::Complete {
912 verified: 4,
913 total: 4,
914 built: 0,
915 rechecked: 2,
916 changed: vec!["core".into()],
917 suite: None,
918 model_calls: 0,
919 },
920 ),
921 ]
922 }
923
924 #[test]
925 fn final_report_aligns_one_line_per_sdd() {
926 assert_eq!(
927 report(&sample_report()).join("\n"),
928 "Blocked.\n\
929 \x20 api Blocked U-007 rotten: row 2 broke at a1b2c3d (core U-004 integrated) — culprit found\n\
930 \x20 cli Complete 4/4 Verified · re-checked 2 (core changed), no model calls\n\
931 \x20 core Complete 12/12 Verified · built 3 · §5 Test passing\n\
932 \x20 docs Up to date nothing changed since 9f3c2e1\n\
933 \x20 web Blocked U-004 waits on api U-007 (rotten)"
934 );
935 }
936
937 #[test]
938 fn final_report_is_complete_when_nothing_is_blocked() {
939 let lanes: Vec<LaneReport> = sample_report()
940 .into_iter()
941 .filter(|l| l.state() != LaneState::Blocked)
942 .collect();
943 let lines = report(&lanes);
944 assert_eq!(lines[0], "Complete.");
945 assert_eq!(lines.len(), 4);
946 }
947
948 #[test]
949 fn project_json_has_a_fixed_key_order_and_is_deterministic() {
950 let rec = ProjectRecord {
951 started_at: "2026-11-21T10:15:00Z".into(),
952 ended_at: None,
953 plan: sample_plan(),
954 critical_path_ran: vec![n("core", "U-001"), n("core", "U-002")],
955 };
956 let text = rec.to_json().dumps_indent2();
957 assert_eq!(text, rec.clone().to_json().dumps_indent2());
958 let keys: Vec<&str> = text
959 .lines()
960 .filter(|l| l.starts_with(" \""))
961 .map(|l| l.trim().split('"').nth(1).unwrap())
962 .collect();
963 assert_eq!(
964 keys,
965 [
966 "job_id",
967 "started_at",
968 "ended_at",
969 "capacity",
970 "lanes",
971 "regenerate",
972 "adopt",
973 "recheck",
974 "critical_path",
975 "critical_path_ran"
976 ]
977 );
978 assert!(text.contains("\"state\": \"up to date\""));
979 assert!(text.contains("\"why\": \"core/src/lib.rs (unit core U-002)\""));
980
981 let tmp = tempfile::tempdir().unwrap();
982 let dir = tmp.path().join("logs").join("job");
983 rec.write(&dir).unwrap();
984 let on_disk = std::fs::read_to_string(dir.join("project.json")).unwrap();
985 assert_eq!(on_disk, format!("{text}\n"));
986 }
987
988 struct Repo {
991 _tmp: tempfile::TempDir,
992 root: std::path::PathBuf,
993 }
994
995 impl Repo {
996 fn new() -> Repo {
997 let tmp = tempfile::tempdir().unwrap();
998 let root = tmp.path().canonicalize().unwrap();
999 Repo { _tmp: tmp, root }
1000 }
1001
1002 fn write(&self, rel: &str, text: &str) {
1003 let p = self.root.join(rel);
1004 std::fs::create_dir_all(p.parent().unwrap()).unwrap();
1005 std::fs::write(p, text).unwrap();
1006 }
1007
1008 fn instances(&self) -> Vec<Instance> {
1009 model::discover(&self.root)
1010 .into_iter()
1011 .map(|h| Instance::load(h).unwrap())
1012 .collect()
1013 }
1014
1015 fn bundle(
1018 &self,
1019 slug: &str,
1020 schema: &str,
1021 contracts: &[(&str, &str)],
1022 units: &[(&str, &[&str], &[&str])],
1023 ) {
1024 self.write(
1025 &format!("specs/{slug}/sdd.md"),
1026 &format!(
1027 "---\nsdd: {slug}\ntitle: {slug}\nschema_version: {schema}\nversion: 1.0.0\nstatus: Active\nscope_roots:\n - x/\n---\n\n# {slug}\n\n## Ground Rules\n\nOne implementer per unit.\n"
1028 ),
1029 );
1030 for (id, header) in contracts {
1031 self.write(
1032 &format!("specs/{slug}/contracts/{id}-c.md"),
1033 &format!(
1034 "# {id} — contract\n\n{header}\n- Consumers: —\n- Stability: Frozen\n\n## Surface\n\nsurface of {id}\n"
1035 ),
1036 );
1037 }
1038 for (id, deps, consumes) in units {
1039 self.write(
1040 &format!("specs/{slug}/units/{id}-u.md"),
1041 &format!(
1042 "---\nunit: {id}\ntitle: {id} t\nstatus: Ready\nclaimed_by: —\nclaim_expires: —\nclaim_seq: 0\ndepends_on: [{}]\nparallel_group: —\nowns: [x/{slug}/{id}]\nconsumes: [{}]\n---\n\n# {id} — unit\n",
1043 deps.join(", "),
1044 consumes.join(", ")
1045 ),
1046 );
1047 }
1048 }
1049 }
1050
1051 const PRODUCED_BY_U1: &str = "- Producer: U-001";
1052 const PRODUCED_BY_U2: &str = "- Producer: U-002";
1053 const PIN_CORE_C1: &str =
1054 "- Producer: external — core, C-001\n- Pin: core C-001 @ 000000000000";
1055 const PIN_API_C1: &str = "- Producer: external — api, C-001\n- Pin: api C-001 @ 000000000000";
1056
1057 fn two_sdds(repo: &Repo) {
1059 repo.bundle(
1060 "core",
1061 "2.1",
1062 &[("C-001", PRODUCED_BY_U1)],
1063 &[("U-001", &[], &[]), ("U-002", &["U-001"], &[])],
1064 );
1065 repo.bundle(
1066 "api",
1067 "2.1",
1068 &[("C-001", PIN_CORE_C1)],
1069 &[
1070 ("U-001", &["C-001"], &["C-001"]),
1071 ("U-002", &["U-001"], &[]),
1072 ],
1073 );
1074 }
1075
1076 #[test]
1077 fn a_sound_repository_passes_preflight() {
1078 let repo = Repo::new();
1079 two_sdds(&repo);
1080 let graph = preflight(&repo.instances()).unwrap();
1081 assert_eq!(graph.slugs(), ["api", "core"]);
1082 }
1083
1084 #[test]
1085 fn a_2_0_sdd_consuming_a_pin_is_refused_with_exit_4_naming_every_sdd() {
1086 let repo = Repo::new();
1087 repo.bundle(
1088 "core",
1089 "2.1",
1090 &[("C-001", PRODUCED_BY_U1)],
1091 &[("U-001", &[], &[])],
1092 );
1093 repo.bundle(
1094 "api",
1095 "2.0",
1096 &[("C-001", PIN_CORE_C1)],
1097 &[("U-001", &[], &["C-001"])],
1098 );
1099 repo.bundle(
1100 "web",
1101 "2.0",
1102 &[("C-001", PIN_CORE_C1)],
1103 &[("U-001", &[], &["C-001"])],
1104 );
1105 let refused = preflight(&repo.instances()).unwrap_err();
1106 assert_eq!(refused.code, 4);
1107 assert_eq!(refused.failures.len(), 2);
1108 assert!(refused.failures[0].starts_with("SDD api ("));
1109 assert!(refused.failures[1].starts_with("SDD web ("));
1110 assert!(
1111 refused
1112 .failures
1113 .iter()
1114 .all(|f| f.contains("schema 2.0") && f.contains(" → migrate it to schema 2.1"))
1115 );
1116 }
1117
1118 #[test]
1119 fn unresolved_depends_on_and_authorities_without_producers_exit_2() {
1120 let repo = Repo::new();
1121 repo.bundle(
1122 "core",
1123 "2.1",
1124 &[("C-001", "- Producer: external — a vendor")],
1125 &[("U-001", &[], &[])],
1126 );
1127 repo.bundle(
1128 "api",
1129 "2.1",
1130 &[("C-001", PIN_CORE_C1)],
1131 &[("U-001", &["C-001", "U-009"], &["C-001"])],
1132 );
1133 let refused = preflight(&repo.instances()).unwrap_err();
1134 assert_eq!(refused.code, 2);
1135 assert_eq!(refused.failures.len(), 2, "{:?}", refused.failures);
1136 assert!(
1137 refused
1138 .failures
1139 .iter()
1140 .any(|f| f.starts_with("[L12] api U-001:"))
1141 );
1142 assert!(
1143 refused
1144 .failures
1145 .iter()
1146 .any(|f| f.starts_with("[L1] api U-001:"))
1147 );
1148 assert!(refused.failures.iter().all(|f| f.contains(" → ")));
1149 }
1150
1151 #[test]
1152 fn a_cycle_through_pins_is_reported_as_its_path_with_the_units_behind_it() {
1153 let repo = Repo::new();
1154 repo.bundle(
1155 "core",
1156 "2.1",
1157 &[("C-001", PRODUCED_BY_U1), ("C-002", PIN_API_C1)],
1158 &[("U-001", &["C-002"], &["C-002"])],
1159 );
1160 repo.bundle(
1161 "api",
1162 "2.1",
1163 &[("C-001", PIN_CORE_C1)],
1164 &[
1165 ("U-001", &["C-001"], &["C-001"]),
1166 ("U-002", &["U-001"], &[]),
1167 ],
1168 );
1169 repo.write(
1172 "specs/api/contracts/C-002-c.md",
1173 "# C-002 — contract\n\n- Producer: U-001\n- Consumers: —\n- Stability: Frozen\n\n## Surface\n\ns\n",
1174 );
1175 repo.write(
1176 "specs/core/contracts/C-002-c.md",
1177 "# C-002 — contract\n\n- Producer: external — api, C-002\n- Consumers: —\n- Stability: Frozen by its producer\n- Pin: api C-002 @ 000000000000\n",
1178 );
1179 let refused = preflight(&repo.instances()).unwrap_err();
1180 assert_eq!(refused.code, 2);
1181 assert_eq!(
1182 refused.failures,
1183 vec![
1184 "[L12] dependency cycle: api U-001 → core U-001 → api U-001 → break the cycle: remove one depends_on entry on that path".to_string(),
1185 "1 unit waits behind a cycle: api U-002 → waiting units build once the cycle is broken"
1186 .to_string(),
1187 ]
1188 );
1189 }
1190
1191 #[test]
1192 fn shared_slugs_are_refused() {
1193 let repo = Repo::new();
1194 repo.bundle("core", "2.1", &[], &[("U-001", &[], &[])]);
1195 repo.write(
1197 "specs/other/sdd.md",
1198 "---\nsdd: core\ntitle: x\nschema_version: 2.1\nversion: 1.0.0\nstatus: Active\nscope_roots:\n - y/\n---\n\n# x\n",
1199 );
1200 let refused = preflight(&repo.instances()).unwrap_err();
1201 assert_eq!(refused.code, 2);
1202 assert!(refused.failures[0].starts_with("several SDDs have the slug `core`: "));
1203 assert!(refused.failures[0].contains(" → give each SDD"));
1204 }
1205
1206 #[test]
1209 fn lane_selection_takes_the_lane_and_what_it_depends_on() {
1210 let repo = Repo::new();
1211 two_sdds(&repo);
1212 repo.bundle(
1213 "web",
1214 "2.1",
1215 &[(
1216 "C-001",
1217 "- Producer: external — api, C-002\n- Pin: api C-002 @ 000000000000",
1218 )],
1219 &[("U-001", &["C-001"], &["C-001"])],
1220 );
1221 repo.bundle(
1222 "api",
1223 "2.1",
1224 &[("C-001", PIN_CORE_C1), ("C-002", PRODUCED_BY_U2)],
1225 &[
1226 ("U-001", &["C-001"], &["C-001"]),
1227 ("U-002", &["U-001"], &[]),
1228 ],
1229 );
1230 let graph = preflight(&repo.instances()).unwrap();
1231 assert_eq!(select_lanes(&graph, "ghost", true), None);
1232 assert_eq!(select_lanes(&graph, "web", false).unwrap(), ["web"]);
1233 assert_eq!(
1234 select_lanes(&graph, "web", true).unwrap(),
1235 ["api", "core", "web"]
1236 );
1237 assert_eq!(select_lanes(&graph, "core", true).unwrap(), ["core"]);
1238 }
1239
1240 #[test]
1241 fn units_waiting_outside_the_selection_end_as_named_blockers() {
1242 let repo = Repo::new();
1243 two_sdds(&repo);
1244 let graph = preflight(&repo.instances()).unwrap();
1245 let selected = select_lanes(&graph, "api", false).unwrap();
1246 let ready = |_: &Node| Some("Ready".to_string());
1247 assert_eq!(
1248 outside_blocker(&graph, &selected, &n("api", "U-001"), &ready).unwrap(),
1249 "U-001 waits on core U-001, outside this run (SDD core not selected; --upstream builds it)"
1250 );
1251 assert_eq!(
1253 outside_blocker(&graph, &selected, &n("api", "U-002"), &ready),
1254 None
1255 );
1256 let all = select_lanes(&graph, "api", true).unwrap();
1257 assert_eq!(
1258 outside_blocker(&graph, &all, &n("api", "U-001"), &ready),
1259 None
1260 );
1261 let verified = |_: &Node| Some("Verified".to_string());
1263 assert_eq!(
1264 outside_blocker(&graph, &selected, &n("api", "U-001"), &verified),
1265 None
1266 );
1267 let retired = |_: &Node| Some("Retired".to_string());
1268 assert!(outside_blocker(&graph, &selected, &n("api", "U-001"), &retired).is_some());
1269 }
1270}