1use std::collections::BTreeSet;
14use std::io::Read;
15use std::path::{Path, PathBuf};
16use std::time::{SystemTime, UNIX_EPOCH};
17
18use serde_json::Value;
19use vitrify_core::graph::{Node, UnitGraph, slug_of};
20use vitrify_core::model::{Instance, UtcTime};
21use vitrify_core::{CoreError, ledger};
22
23use super::render::{died_line, duration, hhmmss, kill_line};
24use crate::cmd;
25use crate::git::Git;
26use crate::signals;
27
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30pub enum RunState {
31 Alive,
33 Died,
35 Ended,
37}
38
39impl RunState {
40 pub fn as_str(self) -> &'static str {
41 match self {
42 RunState::Alive => "alive",
43 RunState::Died => "died",
44 RunState::Ended => "ended",
45 }
46 }
47}
48
49#[derive(Debug, Clone, PartialEq)]
51pub struct Terminated {
52 pub state: String,
54 pub at: String,
55 pub detail: String,
56}
57
58#[derive(Debug, Clone, Default, PartialEq)]
60pub struct Params {
61 pub cap: i64,
62 pub gate_jobs: i64,
63 pub lease_minutes: i64,
64 pub worker_timeout_minutes: i64,
65}
66
67#[derive(Debug, Clone, PartialEq)]
69pub struct GateView {
70 pub step: String,
71 pub since: Option<UtcTime>,
72 pub batch: Vec<String>,
73 pub running: Vec<(String, Option<UtcTime>)>,
75 pub done: Option<i64>,
76 pub total: Option<i64>,
77}
78
79#[derive(Debug, Clone, PartialEq)]
82pub struct WorkerView {
83 pub unit: String,
84 pub claim_seq: i64,
85 pub holder: String,
86 pub pid: u32,
88 pub retry: bool,
89 pub worktree: String,
90 pub lane: String,
93 pub started_at: String,
94 pub ended_at: Option<String>,
95 pub outcome: String,
96 pub stage: String,
99 pub alive: Option<bool>,
102 pub log_bytes: Option<u64>,
103 pub log_quiet_s: Option<i64>,
104 pub files_changed: Option<u64>,
105 pub insertions: Option<u64>,
106 pub deletions: Option<u64>,
107 pub carried_over: Option<u64>,
108 pub stamped: Option<bool>,
109 pub detail: Option<String>,
111 pub error: Option<String>,
113}
114
115impl WorkerView {
116 pub fn started(&self) -> Option<UtcTime> {
117 UtcTime::parse(&self.started_at)
118 }
119
120 pub fn ended(&self) -> Option<UtcTime> {
121 self.ended_at.as_deref().and_then(UtcTime::parse)
122 }
123}
124
125#[derive(Debug, Clone, PartialEq)]
128pub struct LaneView {
129 pub slug: String,
131 pub root: String,
133 pub state: String,
136 pub verified: Option<u64>,
138 pub total: Option<u64>,
140 pub in_flight: u64,
142 pub waiting: Option<u64>,
144 pub waits_on: Vec<String>,
147}
148
149#[derive(Debug, Clone, PartialEq)]
151pub struct Snapshot {
152 pub job_id: String,
153 pub pid: u32,
154 pub sdd: String,
155 pub harness: String,
156 pub started_at: String,
157 pub at: UtcTime,
159 pub state: RunState,
160 pub terminated: Option<Terminated>,
161 pub report: Option<Vec<String>>,
163 pub progress: Option<String>,
165 pub params: Params,
166 pub workers: Vec<WorkerView>,
168 pub lanes: Vec<LaneView>,
171 pub gate: Option<GateView>,
173 pub warnings: Vec<String>,
174 pub logs: String,
176}
177
178pub fn take(root: &Path, job: &str, now: UtcTime, quiet_after: u64) -> Result<Snapshot, CoreError> {
181 let scratch = root.join(".vitrify");
182 let logs_dir = scratch.join("logs").join(job);
183 let path = logs_dir.join("run.json");
185 let text = match std::fs::read_to_string(&path) {
186 Ok(text) => text,
187 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
188 return Err(CoreError::refusal(
189 4,
190 format!("error: no run recorded as {job}"),
191 ));
192 }
193 Err(e) => return Err(super::cannot_read(&path, e)),
194 };
195 let v: Value = serde_json::from_str(&text).map_err(|e| super::cannot_read(&path, e))?;
196
197 let pid = as_u32(&v["pid"]);
198 let sdd = str_of(&v["sdd"]);
199 let terminated = v["terminated"].as_object().map(|t| Terminated {
200 state: t.get("state").map(str_of).unwrap_or_default(),
201 at: t.get("at").map(str_of).unwrap_or_default(),
202 detail: t.get("detail").map(str_of).unwrap_or_default(),
203 });
204 let report = v["report"].as_array().map(|lines| {
205 lines
206 .iter()
207 .map(|l| l.as_str().unwrap_or_default().to_string())
208 .collect()
209 });
210 let state = if terminated.is_some() {
213 RunState::Ended
214 } else if signals::alive(pid, false)
215 && scratch.join("jobs").join(format!("{job}.lock")).exists()
216 {
217 RunState::Alive
218 } else {
219 RunState::Died
220 };
221 let progress = cmd::resolve_sdd_in(root, Path::new(&sdd))
222 .and_then(Instance::load)
223 .ok()
224 .map(|inst| ledger::progress_line(&inst.units));
225 let p = &v["params"];
226 let params = Params {
227 cap: p["cap"].as_i64().unwrap_or(0),
228 gate_jobs: p["gate_jobs"].as_i64().unwrap_or(0),
229 lease_minutes: p["lease_minutes"].as_i64().unwrap_or(0),
230 worker_timeout_minutes: p["worker_timeout_minutes"].as_i64().unwrap_or(0),
231 };
232 let lanes = lane_dirs(&logs_dir);
233 let gate = if state == RunState::Alive {
234 let boards: Vec<GateView> = lanes
236 .iter()
237 .filter_map(|(_, dir)| std::fs::read_to_string(dir.join("gate.json")).ok())
238 .filter_map(|t| serde_json::from_str::<Value>(&t).ok())
239 .filter_map(|g| parse_gate(&g))
240 .collect();
241 let busy = boards.iter().position(|g| g.step != "idle").unwrap_or(0);
242 boards.into_iter().nth(busy)
243 } else {
244 None
245 };
246
247 let mut workers = Vec::new();
248 for w in v["workers"].as_array().map(Vec::as_slice).unwrap_or(&[]) {
249 let mut view = WorkerView {
250 unit: str_of(&w["unit"]),
251 claim_seq: w["claim_seq"].as_i64().unwrap_or(0),
252 holder: str_of(&w["holder"]),
253 pid: as_u32(&w["pid"]),
254 retry: w["retry"].as_bool().unwrap_or(false),
255 worktree: str_of(&w["worktree"]),
256 lane: str_of(&w["lane"]),
257 started_at: str_of(&w["started_at"]),
258 ended_at: w["ended_at"].as_str().map(str::to_string),
259 outcome: str_of(&w["outcome"]),
260 stage: String::new(),
261 alive: None,
262 log_bytes: None,
263 log_quiet_s: None,
264 files_changed: None,
265 insertions: None,
266 deletions: None,
267 carried_over: None,
268 stamped: None,
269 detail: w["detail"].as_str().map(str::to_string),
270 error: None,
271 };
272 if view.outcome == "running" {
273 let lane = w["lane"].as_str();
276 let dir = lanes
277 .iter()
278 .find(|(slug, _)| Some(slug.as_str()) == lane)
279 .or(lanes.first())
280 .map_or(logs_dir.as_path(), |(_, dir)| dir.as_path());
281 probe(&mut view, dir, &sdd, now);
282 }
283 view.stage = stage(&view, state, gate.as_ref());
284 workers.push(view);
285 }
286
287 let lane_views = lane_views(root, &logs_dir, &sdd, terminated.as_ref(), &workers);
288 let mut snap = Snapshot {
289 job_id: v["job_id"].as_str().unwrap_or(job).to_string(),
290 pid,
291 sdd,
292 harness: str_of(&v["harness"]),
293 started_at: str_of(&v["started_at"]),
294 at: now,
295 state,
296 terminated,
297 report,
298 progress,
299 params,
300 workers,
301 lanes: lane_views,
302 gate,
303 warnings: Vec::new(),
304 logs: format!(".vitrify/logs/{job}/"),
305 };
306 snap.warnings = warnings(&snap, quiet_after);
307 Ok(snap)
308}
309
310struct LaneRecord {
312 slug: String,
313 root: String,
316 state: String,
317 units: Option<u64>,
319 verified: Option<u64>,
320}
321
322fn project_lanes(logs_dir: &Path) -> Option<Vec<LaneRecord>> {
325 let project = fs_err::read_to_string(logs_dir.join("project.json"))
326 .ok()
327 .and_then(|t| serde_json::from_str::<Value>(&t).ok())?;
328 let lanes = project["lanes"]
329 .as_array()
330 .map(Vec::as_slice)
331 .unwrap_or(&[])
332 .iter()
333 .filter_map(|l| {
334 let slug = l["slug"].as_str()?;
335 if slug.is_empty() || slug.contains('/') || slug == ".." {
337 return None;
338 }
339 let root = l["root"].as_str().or(l["sdd"].as_str());
340 Some(LaneRecord {
341 slug: slug.to_string(),
342 root: root.unwrap_or_default().to_string(),
343 state: str_of(&l["state"]),
344 units: l["units"].as_u64(),
345 verified: l["verified"].as_u64(),
346 })
347 })
348 .collect();
349 Some(lanes)
350}
351
352pub fn lane_dirs(logs_dir: &Path) -> Vec<(String, PathBuf)> {
356 match project_lanes(logs_dir) {
357 Some(lanes) => lanes
358 .into_iter()
359 .map(|l| {
360 let dir = logs_dir.join(&l.slug);
361 (l.slug, dir)
362 })
363 .collect(),
364 None => vec![(String::new(), logs_dir.to_path_buf())],
365 }
366}
367
368fn load_sdd(root: &Path, rel: &str) -> Option<Instance> {
370 if rel.is_empty() {
371 return None;
372 }
373 cmd::resolve_sdd_in(root, Path::new(rel))
374 .and_then(Instance::load)
375 .ok()
376}
377
378fn lane_views(
384 root: &Path,
385 logs_dir: &Path,
386 sdd: &str,
387 terminated: Option<&Terminated>,
388 workers: &[WorkerView],
389) -> Vec<LaneView> {
390 let records = project_lanes(logs_dir).unwrap_or_else(|| {
391 let state = match terminated.map(|t| t.state.as_str()) {
392 None => "build",
393 Some("complete") => "complete",
394 Some(_) => "blocked",
395 };
396 vec![LaneRecord {
397 slug: String::new(),
398 root: sdd.to_string(),
399 state: state.to_string(),
400 units: None,
401 verified: None,
402 }]
403 });
404 let insts: Vec<Option<Instance>> = records.iter().map(|r| load_sdd(root, &r.root)).collect();
405 let graph = if records
406 .iter()
407 .any(|r| r.state == "idle" || r.state == "blocked")
408 {
409 let loaded: Vec<Instance> = insts.iter().flatten().cloned().collect();
410 UnitGraph::build(&loaded).ok()
411 } else {
412 None
413 };
414
415 records
416 .iter()
417 .zip(&insts)
418 .enumerate()
419 .map(|(i, (rec, inst))| {
420 let in_flight = workers
422 .iter()
423 .filter(|w| w.outcome == "running" || w.outcome == "integrating")
424 .filter(|w| {
425 w.lane == rec.slug || (i == 0 && !records.iter().any(|r| r.slug == w.lane))
426 })
427 .count() as u64;
428 let counts = match inst {
429 Some(inst) => {
430 let live: Vec<&str> = inst
431 .units
432 .iter()
433 .map(|u| u.meta.get_str_or("status", "Draft"))
434 .filter(|s| *s != "Retired")
435 .collect();
436 let verified = live.iter().filter(|s| **s == "Verified").count();
437 Some((verified as u64, live.len() as u64))
438 }
439 None => rec.verified.zip(rec.units),
440 };
441 let slug = match inst {
443 Some(inst) if rec.slug.is_empty() => slug_of(inst).to_string(),
444 _ => rec.slug.clone(),
445 };
446 let waits_on = match (&graph, rec.state.as_str()) {
447 (Some(g), "idle" | "blocked") => waits_on_of(g, &slug),
448 _ => Vec::new(),
449 };
450 LaneView {
451 slug,
452 root: rec.root.clone(),
453 state: rec.state.clone(),
454 verified: counts.map(|c| c.0),
455 total: counts.map(|c| c.1),
456 in_flight,
457 waiting: counts.map(|(v, t)| t.saturating_sub(v).saturating_sub(in_flight)),
458 waits_on,
459 }
460 })
461 .collect()
462}
463
464fn waits_on_of(graph: &UnitGraph, slug: &str) -> Vec<String> {
468 let done = |n: &Node| matches!(graph.status(n), Some("Verified" | "Retired"));
469 let released = |n: &Node| done(n) || graph.status(n) == Some("Built");
470 let mut out: BTreeSet<&Node> = BTreeSet::new();
471 for n in graph.nodes().iter().filter(|n| n.slug == slug && !done(n)) {
472 out.extend(
473 graph
474 .dependencies(n)
475 .into_iter()
476 .filter(|d| d.slug != slug && !released(d)),
477 );
478 }
479 out.into_iter().map(Node::to_string).collect()
480}
481
482fn str_of(v: &Value) -> String {
484 v.as_str().unwrap_or_default().to_string()
485}
486
487fn as_u32(v: &Value) -> u32 {
489 v.as_u64().and_then(|n| u32::try_from(n).ok()).unwrap_or(0)
490}
491
492pub fn parse_gate(g: &Value) -> Option<GateView> {
494 let g = g.as_object()?;
495 let strings = |v: Option<&Value>| -> Vec<String> {
496 v.and_then(Value::as_array)
497 .map(|a| {
498 a.iter()
499 .filter_map(Value::as_str)
500 .map(str::to_string)
501 .collect()
502 })
503 .unwrap_or_default()
504 };
505 let running = g
506 .get("running")
507 .and_then(Value::as_array)
508 .map(|a| {
509 a.iter()
510 .map(|r| {
511 (
512 str_of(&r["command"]),
513 r["since"].as_str().and_then(UtcTime::parse),
514 )
515 })
516 .collect()
517 })
518 .unwrap_or_default();
519 Some(GateView {
520 step: g.get("step").map(str_of).unwrap_or_default(),
521 since: g
522 .get("since")
523 .and_then(Value::as_str)
524 .and_then(UtcTime::parse),
525 batch: strings(g.get("batch")),
526 running,
527 done: g.get("done").and_then(Value::as_i64),
528 total: g.get("total").and_then(Value::as_i64),
529 })
530}
531
532fn probe(w: &mut WorkerView, logs_dir: &Path, sdd: &str, now: UtcTime) {
535 w.alive = Some(signals::alive(w.pid, true));
536
537 let mut bytes = None;
538 let mut latest: Option<i64> = None;
539 for ext in ["out", "err"] {
540 if let Ok(meta) = std::fs::metadata(logs_dir.join(format!("worker-{}.{ext}", w.holder))) {
541 bytes = Some(bytes.unwrap_or(0) + meta.len());
542 if let Some(t) = meta.modified().ok().and_then(epoch) {
543 latest = Some(latest.map_or(t, |l: i64| l.max(t)));
544 }
545 }
546 }
547 w.log_bytes = bytes;
548 w.log_quiet_s = latest.map(|t| (now.0 - t).max(0));
549
550 let wt = Path::new(&w.worktree);
551 if !wt.is_dir() {
552 w.error = Some("worktree missing".to_string());
553 } else {
554 let prompt = std::fs::metadata(logs_dir.join(format!("worker-{}.prompt.md", w.holder)))
555 .and_then(|m| m.modified())
556 .ok();
557 match probe_work(wt, prompt) {
558 Ok(work) => {
559 w.files_changed = Some(work.files);
560 w.insertions = Some(work.insertions);
561 w.deletions = Some(work.deletions);
562 w.carried_over = Some(work.carried_over);
563 }
564 Err(e) => w.error = Some(e),
565 }
566 }
567
568 w.stamped = cmd::resolve_sdd_in(wt, Path::new(sdd))
569 .and_then(Instance::load)
570 .ok()
571 .and_then(|inst| {
572 inst.unit(&w.unit)
573 .map(|u| u.meta.get_str_or("status", "") == "Built")
574 });
575}
576
577fn epoch(t: SystemTime) -> Option<i64> {
579 t.duration_since(UNIX_EPOCH)
580 .ok()
581 .map(|d| d.as_secs() as i64)
582}
583
584struct Work {
586 files: u64,
587 insertions: u64,
588 deletions: u64,
589 carried_over: u64,
590}
591
592const MAX_COUNTED: usize = 500;
594
595fn probe_work(wt: &Path, prompt: Option<SystemTime>) -> Result<Work, String> {
599 let first_line =
600 |e: crate::git::GitError| e.to_string().lines().next().unwrap_or_default().to_string();
601 let git = Git::new(wt);
602 let changes = git.changes_readonly().map_err(first_line)?;
603 let (mut insertions, deletions) = git.numstat_readonly("HEAD").map_err(first_line)?;
604 let mut counted = 0;
605 let mut carried_over = 0;
606 for (xy, path) in &changes {
607 let full = wt.join(path);
608 if xy == "??" && counted < MAX_COUNTED {
609 counted += 1;
610 insertions += count_lines(&full);
611 }
612 let edited = match (prompt, std::fs::metadata(&full).and_then(|m| m.modified())) {
613 (None, _) | (_, Err(_)) => true,
614 (Some(p), Ok(m)) => m > p,
615 };
616 if !edited {
617 carried_over += 1;
618 }
619 }
620 Ok(Work {
621 files: changes.len() as u64,
622 insertions,
623 deletions,
624 carried_over,
625 })
626}
627
628pub fn count_lines(path: &Path) -> u64 {
631 let mut buf = Vec::new();
632 let read = std::fs::File::open(path).and_then(|f| f.take(1024 * 1024).read_to_end(&mut buf));
633 if read.is_err() {
634 return 0;
635 }
636 if buf[..buf.len().min(8192)].contains(&0) {
637 return 0;
638 }
639 let newlines = buf.iter().filter(|&&b| b == b'\n').count() as u64;
640 let unterminated = !buf.is_empty() && buf.last() != Some(&b'\n');
641 newlines + u64::from(unterminated)
642}
643
644pub fn stage(w: &WorkerView, state: RunState, gate: Option<&GateView>) -> String {
647 match w.outcome.as_str() {
648 "running" => {
649 if w.alive == Some(false) {
650 "exited"
651 } else if w.error.is_some() {
652 "unknown"
653 } else if w.stamped == Some(true) {
654 "stamped"
655 } else if w.files_changed.unwrap_or(0) > w.carried_over.unwrap_or(0) {
656 "editing"
657 } else {
658 "reading"
659 }
660 }
661 "integrating" => {
662 if state != RunState::Alive {
663 "integrating"
664 } else if gate.is_some_and(|g| g.batch.contains(&w.unit)) {
665 "gate"
666 } else {
667 "queued"
668 }
669 }
670 other => other,
671 }
672 .to_string()
673}
674
675pub fn warnings(s: &Snapshot, quiet_after: u64) -> Vec<String> {
678 let quiet_after = quiet_after as i64;
679 let running = || s.workers.iter().filter(|w| w.outcome == "running");
680 let elapsed = |w: &WorkerView| w.started().map(|t| (s.at.0 - t.0).max(0));
681 let mut out = Vec::new();
682 for w in running().filter(|w| w.alive == Some(true)) {
683 let label = format!("{} c{}", w.unit, w.claim_seq);
684 let ran = elapsed(w).unwrap_or(0);
685 if w.log_bytes == Some(0) && ran >= quiet_after {
686 out.push(format!("{label}: no output at all after {}", duration(ran)));
687 } else if let Some(q) = w.log_quiet_s.filter(|&q| q >= quiet_after) {
688 out.push(format!(
689 "{label}: no output for {} (since {})",
690 duration(q),
691 hhmmss(UtcTime(s.at.0 - q))
692 ));
693 }
694 }
695 let budget = s.params.worker_timeout_minutes * 60;
696 if budget > 0 {
697 for w in running() {
698 if let Some(ran) = elapsed(w).filter(|&r| r * 10 >= budget * 9) {
699 out.push(format!(
700 "{} c{}: {} of its {} budget used",
701 w.unit,
702 w.claim_seq,
703 duration(ran),
704 duration(budget)
705 ));
706 }
707 }
708 }
709 if s.state == RunState::Died {
710 out.push(died_line(s.pid));
711 for w in running().filter(|w| w.alive == Some(true)) {
712 out.push(kill_line(&s.job_id, w.pid, &w.unit));
713 }
714 }
715 out
716}
717
718#[cfg(test)]
719pub(crate) mod tests {
720 use super::*;
721
722 pub(crate) fn worker(unit: &str, outcome: &str) -> WorkerView {
724 WorkerView {
725 unit: unit.to_string(),
726 claim_seq: 1,
727 holder: "run-x-w1".to_string(),
728 pid: 4242,
729 retry: false,
730 worktree: "/tmp/wt".to_string(),
731 lane: String::new(),
732 started_at: "2026-11-16T14:00:00Z".to_string(),
733 ended_at: None,
734 outcome: outcome.to_string(),
735 stage: String::new(),
736 alive: None,
737 log_bytes: None,
738 log_quiet_s: None,
739 files_changed: None,
740 insertions: None,
741 deletions: None,
742 carried_over: None,
743 stamped: None,
744 detail: None,
745 error: None,
746 }
747 }
748
749 fn gate(batch: &[&str]) -> GateView {
750 GateView {
751 step: "rows".to_string(),
752 since: None,
753 batch: batch.iter().map(|u| u.to_string()).collect(),
754 running: Vec::new(),
755 done: None,
756 total: None,
757 }
758 }
759
760 #[test]
761 fn running_stages() {
762 let alive = RunState::Alive;
763 let mut w = worker("U-001", "running");
764 w.alive = Some(true);
765 w.files_changed = Some(0);
766 w.carried_over = Some(0);
767 assert_eq!(stage(&w, alive, None), "reading");
768 w.files_changed = Some(2);
770 w.carried_over = Some(2);
771 assert_eq!(stage(&w, alive, None), "reading");
772 w.carried_over = Some(1);
773 assert_eq!(stage(&w, alive, None), "editing");
774 w.stamped = Some(true);
775 assert_eq!(stage(&w, alive, None), "stamped");
776 w.error = Some("worktree missing".to_string());
777 assert_eq!(stage(&w, alive, None), "unknown");
778 w.alive = Some(false);
779 assert_eq!(stage(&w, alive, None), "exited");
780 }
781
782 #[test]
783 fn integrating_and_final_stages() {
784 let w = worker("U-002", "integrating");
785 let g = gate(&["U-002"]);
786 assert_eq!(stage(&w, RunState::Alive, Some(&g)), "gate");
787 assert_eq!(
788 stage(&w, RunState::Alive, Some(&gate(&["U-009"]))),
789 "queued"
790 );
791 assert_eq!(stage(&w, RunState::Alive, None), "queued");
792 assert_eq!(stage(&w, RunState::Died, Some(&g)), "integrating");
793 assert_eq!(stage(&w, RunState::Ended, None), "integrating");
794 let done = worker("U-003", "rejected-gate");
795 assert_eq!(stage(&done, RunState::Alive, None), "rejected-gate");
796 }
797
798 #[test]
799 fn untracked_lines() {
800 let dir = std::env::temp_dir().join(format!("vitrify-count-{}", std::process::id()));
801 std::fs::create_dir_all(&dir).unwrap();
802 let file = |name: &str, body: &[u8]| {
803 let p = dir.join(name);
804 std::fs::write(&p, body).unwrap();
805 p
806 };
807 assert_eq!(count_lines(&file("a.txt", b"one\ntwo\n")), 2);
808 assert_eq!(count_lines(&file("b.txt", b"one\ntwo")), 2);
809 assert_eq!(count_lines(&file("c.txt", b"")), 0);
810 assert_eq!(count_lines(&file("d.bin", b"PK\x03\x04\0\0\nmore\n")), 0);
811 assert_eq!(count_lines(&dir.join("missing")), 0);
812 std::fs::remove_dir_all(&dir).unwrap();
813 }
814
815 #[test]
816 fn lane_records_are_found_through_project_json() {
817 let dir = tempfile::tempdir().unwrap();
818 let logs = dir.path();
819 assert_eq!(lane_dirs(logs), vec![(String::new(), logs.to_path_buf())]);
821 std::fs::write(
822 logs.join("project.json"),
823 r#"{"job_id": "run-x", "lanes": [
824 {"sdd": "specs/a", "slug": "a", "state": "build"},
825 {"sdd": "specs/b", "slug": "../b", "state": "build"},
826 {"sdd": "specs/c", "slug": "c", "state": "complete"}]}"#,
827 )
828 .unwrap();
829 assert_eq!(
830 lane_dirs(logs),
831 vec![
832 ("a".to_string(), logs.join("a")),
833 ("c".to_string(), logs.join("c"))
834 ]
835 );
836 }
837
838 #[test]
839 fn both_shapes_of_project_json_name_a_root_and_a_state() {
840 let dir = tempfile::tempdir().unwrap();
841 let logs = dir.path();
842 assert!(project_lanes(logs).is_none());
843 std::fs::write(
845 logs.join("project.json"),
846 r#"{"job_id": "run-x", "lanes": [{"sdd": "specs/a", "slug": "a", "state": "idle"}]}"#,
847 )
848 .unwrap();
849 let lanes = project_lanes(logs).unwrap();
850 assert_eq!(
851 (lanes[0].root.as_str(), lanes[0].state.as_str()),
852 ("specs/a", "idle")
853 );
854 assert_eq!((lanes[0].units, lanes[0].verified), (None, None));
855 std::fs::write(
857 logs.join("project.json"),
858 r#"{"job_id": "run-x", "lanes": [{"slug": "a", "root": "specs/a",
859 "state": "up to date", "units": 4, "verified": 4, "regenerate": 0,
860 "adopt": 0, "recheck": 0}], "critical_path": []}"#,
861 )
862 .unwrap();
863 let lanes = project_lanes(logs).unwrap();
864 assert_eq!(
865 (lanes[0].root.as_str(), lanes[0].state.as_str()),
866 ("specs/a", "up to date")
867 );
868 assert_eq!((lanes[0].units, lanes[0].verified), (Some(4), Some(4)));
869 }
870
871 #[test]
872 fn gate_json_is_read_with_defaults() {
873 let v: Value = serde_json::from_str(
874 r#"{"step": "rows", "since": "2026-11-16T14:08:01Z", "batch": ["U-002"],
875 "running": [{"command": "pytest -q", "since": "2026-11-16T14:08:03Z"}],
876 "done": 3, "total": 7}"#,
877 )
878 .unwrap();
879 let g = parse_gate(&v).unwrap();
880 assert_eq!(g.step, "rows");
881 assert_eq!(g.batch, vec!["U-002"]);
882 assert_eq!(g.running[0].0, "pytest -q");
883 assert_eq!((g.done, g.total), (Some(3), Some(7)));
884 let g = parse_gate(&serde_json::json!({"step": "idle"})).unwrap();
885 assert!(g.batch.is_empty() && g.done.is_none());
886 assert!(parse_gate(&serde_json::json!([])).is_none());
887 }
888}