1use std::collections::BTreeMap;
14use std::io::{BufRead, Read, Write};
15use std::os::unix::process::CommandExt;
16use std::path::Path;
17use std::process::{Command, Stdio};
18use std::time::{Duration, Instant};
19
20use vitrify_core::CoreError;
21use vitrify_core::harness::{self, Profiles, Role};
22
23use crate::home::{self, Origin};
24use crate::out::{J, diag, emit};
25
26pub const CONFIG_LABEL: &str = "~/.vitrify/config.toml";
28
29const HARNESSES: [(&str, &[&[&str]]); 3] = [
34 (
35 "claude",
36 &[&[
37 "claude",
38 "-p",
39 "--output-format",
40 "stream-json",
41 "--verbose",
42 ]],
43 ),
44 ("codex", &[&["codex", "exec", "--json"]]),
45 ("opencode", &[&["opencode", "run", "--format", "json"]]),
46];
47
48const PROBE_PROMPT: &str = "Reply with exactly: OK";
49
50fn probe_timeout() -> Duration {
51 let secs = std::env::var("VITRIFY_PROBE_TIMEOUT_SECS")
52 .ok()
53 .and_then(|v| v.parse().ok())
54 .unwrap_or(60u64);
55 Duration::from_secs(secs)
56}
57
58enum ProbeResult {
59 Ok,
61 Failed,
62 TimedOut,
63 Missing,
64}
65
66fn probe(argv: &[&str], timeout: Duration) -> ProbeResult {
68 let mut cmd = Command::new(argv[0]);
69 cmd.args(&argv[1..])
70 .arg(PROBE_PROMPT)
71 .stdin(Stdio::null())
72 .stdout(Stdio::piped())
73 .stderr(Stdio::null())
74 .process_group(0);
75 let mut child = match cmd.spawn() {
76 Ok(c) => c,
77 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return ProbeResult::Missing,
78 Err(_) => return ProbeResult::Failed,
79 };
80 let pid = child.id();
81 let start = Instant::now();
82 loop {
83 match child.try_wait() {
84 Ok(Some(status)) => {
85 let mut out = String::new();
86 if let Some(mut stdout) = child.stdout.take() {
87 let _ = stdout.read_to_string(&mut out);
88 }
89 return if status.success() && !out.trim().is_empty() {
90 ProbeResult::Ok
91 } else {
92 ProbeResult::Failed
93 };
94 }
95 Ok(None) => {
96 if start.elapsed() > timeout {
97 crate::gate::kill_group(pid);
98 let _ = child.wait();
99 return ProbeResult::TimedOut;
100 }
101 std::thread::sleep(Duration::from_millis(50));
102 }
103 Err(_) => return ProbeResult::Failed,
104 }
105 }
106}
107
108fn version_of(bin: &str) -> Option<String> {
109 let out = Command::new(bin)
110 .arg("--version")
111 .stdin(Stdio::null())
112 .output()
113 .ok()?;
114 if !out.status.success() {
115 return None;
116 }
117 String::from_utf8(out.stdout)
118 .ok()
119 .and_then(|s| s.lines().next().map(str::trim).map(str::to_string))
120}
121
122pub(crate) struct HarnessReport {
123 name: &'static str,
124 present: bool,
125 version: Option<String>,
126 headless: Option<Vec<String>>,
127 failure: Option<String>,
128}
129
130pub(crate) struct CheckLine {
131 pub status: &'static str, pub text: String,
133}
134
135impl CheckLine {
136 pub fn new(status: &'static str, text: impl Into<String>) -> CheckLine {
137 CheckLine {
138 status,
139 text: text.into(),
140 }
141 }
142}
143
144pub(crate) struct Probed {
147 pub checks: Vec<CheckLine>,
148 harnesses: Vec<HarnessReport>,
149 git_present: bool,
150 git_version: Option<String>,
151}
152
153impl Probed {
154 pub fn failed(&self) -> bool {
155 self.checks.iter().any(|c| c.status == "FAIL")
156 }
157}
158
159pub(crate) fn probe_machine(
163 home_dir: &Path,
164 version: &str,
165 config_text: &str,
166) -> Result<Probed, CoreError> {
167 let timeout = probe_timeout();
168 let mut checks: Vec<CheckLine> = Vec::new();
169
170 let git_version = version_of("git");
172 let git_present = git_version.is_some();
173 checks.push(match &git_version {
174 Some(v) => CheckLine::new("ok", format!("git present ({v})")),
175 None => CheckLine::new("FAIL", "git not found on PATH"),
176 });
177
178 let mut harnesses: Vec<HarnessReport> = Vec::new();
180 for (name, spellings) in HARNESSES {
181 let hv = version_of(name);
182 if hv.is_none() && Command::new(name).arg("--help").output().is_err() {
183 checks.push(CheckLine::new(
184 "untested",
185 format!("harness {name}: CLI not on PATH"),
186 ));
187 harnesses.push(HarnessReport {
188 name,
189 present: false,
190 version: None,
191 headless: None,
192 failure: None,
193 });
194 continue;
195 }
196 let mut recorded: Option<Vec<String>> = None;
197 let mut failure = None;
198 for argv in spellings.iter() {
199 match probe(argv, timeout) {
200 ProbeResult::Ok => {
201 recorded = Some(argv.iter().map(|s| s.to_string()).collect());
202 break;
203 }
204 ProbeResult::Missing => {
205 failure = Some(format!("harness {name}: CLI not on PATH"));
206 break;
207 }
208 ProbeResult::TimedOut => {
209 failure = Some(format!(
210 "harness {name}: probe timed out after {}s ({})",
211 timeout.as_secs(),
212 argv.join(" ")
213 ));
214 }
215 ProbeResult::Failed => {
216 failure = Some(format!(
217 "harness {name}: headless probe failed — vitrify needs `{}`; update {name} until it accepts it",
218 argv.join(" ")
219 ));
220 }
221 }
222 }
223 match (&recorded, &failure) {
224 (Some(argv), _) => checks.push(CheckLine::new(
225 "ok",
226 format!("harness {name}: headless = {}", argv.join(" ")),
227 )),
228 (None, Some(f)) if f.ends_with("not on PATH") => {
229 checks.push(CheckLine::new("untested", f.clone()));
230 }
231 (None, Some(f)) => checks.push(CheckLine::new("FAIL", f.clone())),
232 (None, None) => {}
233 }
234 let present =
235 recorded.is_some() || !failure.as_deref().unwrap_or("").ends_with("not on PATH");
236 harnesses.push(HarnessReport {
237 name,
238 present,
239 version: hv,
240 headless: recorded,
241 failure,
242 });
243 }
244
245 let states = home::ensure_materialized(home_dir, version)?;
247 let overrides: Vec<_> = states
248 .iter()
249 .filter(|s| s.origin == Origin::Override)
250 .collect();
251 checks.push(CheckLine::new(
252 "ok",
253 format!(
254 "~/.vitrify materialized ({} assets, {} overridden)",
255 states.len(),
256 overrides.len()
257 ),
258 ));
259 for s in &overrides {
260 checks.push(CheckLine::new(
261 "note",
262 if s.stale_against_embedded {
263 format!(
264 "override: {} (forked from another shipped version — stale against embedded)",
265 s.rel_path
266 )
267 } else {
268 format!("override: {}", s.rel_path)
269 },
270 ));
271 }
272
273 match harness::parse(config_text, CONFIG_LABEL) {
275 Ok(profiles) => {
276 for h in harnesses.iter() {
279 let Some(recorded) = &h.headless else {
280 continue;
281 };
282 let profile = profiles.get(h.name);
283 for role in Role::ALL {
284 if !profile.is_own(role) {
285 continue; }
287 let label = format!("harness {} {}", h.name, role.as_str());
288 let described = profile.describe(role);
289 if profile.role_args(role).is_empty() {
290 checks.push(CheckLine::new("ok", format!("{label}: {described}")));
291 continue;
292 }
293 let argv = profiles.argv_for(h.name, recorded, role);
294 let argv_ref: Vec<&str> = argv.iter().map(String::as_str).collect();
295 checks.push(match probe(&argv_ref, timeout) {
296 ProbeResult::Ok => CheckLine::new("ok", format!("{label}: {described}")),
297 ProbeResult::TimedOut => CheckLine::new(
298 "FAIL",
299 format!(
300 "{label}: probe timed out after {}s ({})",
301 timeout.as_secs(),
302 argv.join(" ")
303 ),
304 ),
305 ProbeResult::Failed | ProbeResult::Missing => CheckLine::new(
306 "FAIL",
307 format!(
308 "{label}: probe failed ({}) — fix [harness.{}.{}] in {CONFIG_LABEL}",
309 argv.join(" "),
310 h.name,
311 role.as_str()
312 ),
313 ),
314 });
315 }
316 }
317 }
318 Err(e) => {
319 let msg = e.to_string();
320 checks.push(CheckLine::new(
321 "FAIL",
322 msg.strip_prefix("error: ").unwrap_or(&msg),
323 ));
324 }
325 }
326
327 Ok(Probed {
328 checks,
329 harnesses,
330 git_present,
331 git_version,
332 })
333}
334
335fn toml_str(s: &str) -> String {
339 let mut out = String::from("\"");
340 for c in s.chars() {
341 match c {
342 '"' => out.push_str("\\\""),
343 '\\' => out.push_str("\\\\"),
344 '\n' => out.push_str("\\n"),
345 '\t' => out.push_str("\\t"),
346 c if c.is_control() => out.push_str(&format!("\\u{:04X}", c as u32)),
347 c => out.push(c),
348 }
349 }
350 out.push('"');
351 out
352}
353
354pub(crate) fn render_record(version: &str, p: &Probed) -> String {
356 let mut s = String::from("[probe]\n");
357 s.push_str("# What `vitrify init` and `vitrify probe` found on this machine.\n");
358 s.push_str("# Re-run `vitrify probe` rather than edit these tables.\n");
359 s.push_str(&format!("vitrify_version = {}\n", toml_str(version)));
360 s.push_str(&format!(
361 "git = {{ present = {}, version = {} }}\n",
362 p.git_present,
363 toml_str(p.git_version.as_deref().unwrap_or(""))
364 ));
365 for h in &p.harnesses {
366 s.push_str(&format!("\n[probe.{}]\n", h.name));
367 s.push_str(&format!("present = {}\n", h.present));
368 if let Some(v) = &h.version {
369 s.push_str(&format!("version = {}\n", toml_str(v)));
370 }
371 if let Some(argv) = &h.headless {
372 let quoted: Vec<String> = argv.iter().map(|a| toml_str(a)).collect();
373 s.push_str(&format!("headless = [{}]\n", quoted.join(", ")));
374 }
375 }
376 s
377}
378
379fn header_key(line: &str) -> Option<String> {
382 let t = line.trim_start();
383 let inner = t.strip_prefix("[[").or_else(|| t.strip_prefix('['))?;
384 let end = inner.find(']')?;
385 Some(
386 inner[..end]
387 .split('.')
388 .map(|part| part.trim().trim_matches('"').trim_matches('\''))
389 .collect::<Vec<_>>()
390 .join("."),
391 )
392}
393
394fn is_probe_key(key: &str) -> bool {
395 key == "probe" || key.starts_with("probe.")
396}
397
398pub(crate) fn replace_record(text: &str, block: &str) -> String {
402 let mut out = String::new();
403 let mut in_record = false;
404 let mut placed = false;
405 let mut open: Option<&str> = None;
407 for line in text.split_inclusive('\n') {
408 let header = if open.is_none() {
409 header_key(line)
410 } else {
411 None
412 };
413 for delim in ["\"\"\"", "'''"] {
414 if (open.is_none() || open == Some(delim)) && line.matches(delim).count() % 2 == 1 {
415 open = if open.is_some() { None } else { Some(delim) };
416 }
417 }
418 if let Some(key) = header {
419 if is_probe_key(&key) {
420 if !placed {
421 out.push_str(block);
422 placed = true;
423 }
424 in_record = true;
425 continue;
426 }
427 if in_record && !out.ends_with("\n\n") {
428 out.push('\n');
429 }
430 in_record = false;
431 }
432 if !in_record {
433 out.push_str(line);
434 }
435 }
436 if !placed {
437 if !out.is_empty() && !out.ends_with('\n') {
438 out.push('\n');
439 }
440 if !out.is_empty() && !out.ends_with("\n\n") {
441 out.push('\n');
442 }
443 out.push_str(block);
444 }
445 out
446}
447
448fn flatten_record(table: &toml::Table) -> BTreeMap<String, String> {
451 fn walk(prefix: &str, v: &toml::Value, out: &mut BTreeMap<String, String>) {
452 match v {
453 toml::Value::Table(t) => {
454 for (k, v) in t {
455 walk(&format!("{prefix}.{k}"), v, out);
456 }
457 }
458 toml::Value::String(s) => {
459 out.insert(prefix.to_string(), s.clone());
460 }
461 toml::Value::Array(a) => {
462 let parts: Vec<String> = a
463 .iter()
464 .map(|x| match x {
465 toml::Value::String(s) => s.clone(),
466 other => other.to_string(),
467 })
468 .collect();
469 out.insert(prefix.to_string(), parts.join(" "));
470 }
471 other => {
472 out.insert(prefix.to_string(), other.to_string());
473 }
474 }
475 }
476 let mut out = BTreeMap::new();
477 if let Some(record) = table.get("probe") {
478 walk("probe", record, &mut out);
479 }
480 out
481}
482
483pub(crate) struct Change {
485 pub key: String,
486 pub from: Option<String>,
487 pub to: Option<String>,
488}
489
490impl Change {
491 fn line(&self) -> String {
492 let show = |v: &Option<String>| v.clone().unwrap_or_else(|| "(none)".to_string());
493 format!("{}: {} → {}", self.key, show(&self.from), show(&self.to))
494 }
495}
496
497fn changes(old: &BTreeMap<String, String>, new: &BTreeMap<String, String>) -> Vec<Change> {
498 let mut keys: Vec<&String> = old.keys().chain(new.keys()).collect();
499 keys.sort();
500 keys.dedup();
501 keys.into_iter()
502 .filter(|k| old.get(*k) != new.get(*k))
503 .map(|k| Change {
504 key: k.clone(),
505 from: old.get(k).cloned(),
506 to: new.get(k).cloned(),
507 })
508 .collect()
509}
510
511fn parse_config(text: &str) -> Result<toml::Table, CoreError> {
512 text.parse::<toml::Table>().map_err(|e| {
513 CoreError::refusal(
514 2,
515 format!(
516 "error: unparseable {CONFIG_LABEL}: {e} → fix the line it names, or move the file aside and run vitrify init"
517 ),
518 )
519 })
520}
521
522pub(crate) fn updated_text(text: &str, block: &str) -> Result<String, CoreError> {
525 let new_text = replace_record(text, block);
526 let refuse = |why: &str| {
527 CoreError::refusal(
528 1,
529 format!(
530 "error: cannot update the [probe] tables of {CONFIG_LABEL} in place ({why}) → move them to the end of the file and run vitrify probe again"
531 ),
532 )
533 };
534 let mut before = parse_config(text)?;
535 let mut after = new_text
536 .parse::<toml::Table>()
537 .map_err(|_| refuse("the result does not parse"))?;
538 let expected = block
539 .parse::<toml::Table>()
540 .map_err(|_| refuse("the record does not parse"))?;
541 if after.remove("probe") != expected.get("probe").cloned() {
542 return Err(refuse("the record did not land whole"));
543 }
544 before.remove("probe");
545 if before != after {
546 return Err(refuse("a setting would change"));
547 }
548 Ok(new_text)
549}
550
551pub(crate) fn write_config(home_dir: &Path, text: &str) -> Result<(), CoreError> {
553 let path = home::config_path(home_dir);
554 let tmp = home_dir.join("config.toml.tmp");
555 std::fs::write(&tmp, text).map_err(|source| CoreError::Io {
556 path: tmp.clone(),
557 source,
558 })?;
559 std::fs::rename(&tmp, &path).map_err(|source| CoreError::Io { path, source })
560}
561
562fn plural(n: usize) -> String {
565 if n == 1 {
566 "1 change".to_string()
567 } else {
568 format!("{n} changes")
569 }
570}
571
572enum Answer {
573 Yes,
574 No,
575 NoOne,
577}
578
579fn ask(n: usize) -> Answer {
580 {
581 let mut err = std::io::stderr().lock();
582 let _ = write!(err, "apply {} to {CONFIG_LABEL}? [y/N] ", plural(n));
583 let _ = err.flush();
584 }
585 let mut line = String::new();
586 match std::io::stdin().lock().read_line(&mut line) {
587 Ok(0) | Err(_) => {
588 diag("");
589 Answer::NoOne
590 }
591 Ok(_) => match line.trim().to_ascii_lowercase().as_str() {
592 "y" | "yes" => Answer::Yes,
593 _ => Answer::No,
594 },
595 }
596}
597
598pub(crate) fn json_of(checks: &[CheckLine], p: &Probed, failed: bool) -> Vec<(String, J)> {
600 let jchecks: Vec<J> = checks
601 .iter()
602 .map(|c| {
603 J::Obj(vec![
604 ("status".into(), J::s(c.status)),
605 ("text".into(), J::s(c.text.clone())),
606 ])
607 })
608 .collect();
609 let jh: Vec<J> = p
610 .harnesses
611 .iter()
612 .map(|h| {
613 J::Obj(vec![
614 ("name".into(), J::s(h.name)),
615 ("present".into(), J::Bool(h.present)),
616 ("version".into(), J::opt_str(h.version.clone())),
617 (
618 "headless".into(),
619 match &h.headless {
620 Some(argv) => J::Arr(argv.iter().map(|a| J::s(a.clone())).collect()),
621 None => J::Null,
622 },
623 ),
624 ("failure".into(), J::opt_str(h.failure.clone())),
625 ])
626 })
627 .collect();
628 vec![
629 ("green".into(), J::Bool(!failed)),
630 ("checks".into(), J::Arr(jchecks)),
631 ("harnesses".into(), J::Arr(jh)),
632 ]
633}
634
635pub fn run(json: bool, assume_yes: bool) -> Result<u8, CoreError> {
636 let Some(home_dir) = super::home_dir() else {
637 return Err(CoreError::refusal(
638 1,
639 "error: cannot resolve the vitrify home (set VITRIFY_HOME or HOME)",
640 ));
641 };
642 home::require_set_up(&home_dir)?;
643 let path = home::config_path(&home_dir);
644 let text = vitrify_core::model::read_text(&path)?;
645 let table = parse_config(&text)?;
646 let version = super::brief::VERSION;
647
648 let mut checks = vec![CheckLine::new("ok", format!("vitrify version {version}"))];
649 let probed = probe_machine(&home_dir, version, &text)?;
650 let failed = probed.failed();
651 let block = render_record(version, &probed);
652 let new_text = updated_text(&text, &block)?;
653 let found = changes(
654 &flatten_record(&table),
655 &flatten_record(&parse_config(&new_text)?),
656 );
657 checks.extend(
658 probed
659 .checks
660 .iter()
661 .map(|c| CheckLine::new(c.status, c.text.clone())),
662 );
663 if !json {
664 for c in &checks {
665 emit(&format!("{}: {}", c.status, c.text));
666 }
667 }
668
669 let mut result: Vec<CheckLine> = found
670 .iter()
671 .map(|c| CheckLine::new("change", c.line()))
672 .collect();
673 if !json {
674 for c in &result {
675 emit(&format!("{}: {}", c.status, c.text));
676 }
677 }
678 let applied = if found.is_empty() {
679 result.push(CheckLine::new("ok", format!("{CONFIG_LABEL}: no changes")));
680 false
681 } else {
682 if json && !assume_yes {
683 for c in &result {
685 diag(&format!("{}: {}", c.status, c.text));
686 }
687 }
688 let answer = if assume_yes {
689 Answer::Yes
690 } else {
691 ask(found.len())
692 };
693 match answer {
694 Answer::Yes => {
695 write_config(&home_dir, &new_text)?;
696 result.push(CheckLine::new(
697 "ok",
698 format!("updated {CONFIG_LABEL} ({})", plural(found.len())),
699 ));
700 true
701 }
702 Answer::No => {
703 result.push(CheckLine::new(
704 "note",
705 format!("{CONFIG_LABEL}: nothing changed"),
706 ));
707 false
708 }
709 Answer::NoOne => {
710 result.push(CheckLine::new(
711 "note",
712 format!(
713 "{CONFIG_LABEL}: nothing changed — no answer on stdin; vitrify probe -y applies without asking"
714 ),
715 ));
716 false
717 }
718 }
719 };
720 let declined = !found.is_empty() && !applied;
721
722 if json {
723 let all: Vec<CheckLine> = checks
724 .into_iter()
725 .chain(result.into_iter().filter(|c| c.status != "change"))
726 .collect();
727 let mut obj = json_of(&all, &probed, failed);
728 obj.push((
729 "changes".into(),
730 J::Arr(
731 found
732 .iter()
733 .map(|c| {
734 J::Obj(vec![
735 ("key".into(), J::s(c.key.clone())),
736 ("from".into(), J::opt_str(c.from.clone())),
737 ("to".into(), J::opt_str(c.to.clone())),
738 ])
739 })
740 .collect(),
741 ),
742 ));
743 obj.push(("applied".into(), J::Bool(applied)));
744 emit(&J::Obj(obj).dumps_indent2());
745 } else {
746 for c in result.iter().filter(|c| c.status != "change") {
747 emit(&format!("{}: {}", c.status, c.text));
748 }
749 }
750 Ok(if failed || declined { 2 } else { 0 })
751}
752
753pub fn recorded_headless(home_dir: &Path, harness: &str) -> Option<Vec<String>> {
756 let text = std::fs::read_to_string(home::config_path(home_dir)).ok()?;
757 let table: toml::Table = text.parse().ok()?;
758 let h = table.get("probe")?.as_table()?.get(harness)?.as_table()?;
759 let argv = h.get("headless")?.as_array()?;
760 Some(
761 argv.iter()
762 .filter_map(|v| v.as_str().map(str::to_string))
763 .collect(),
764 )
765}
766
767pub fn role_profiles(home_dir: &Path, repo_root: Option<&Path>) -> Result<Profiles, CoreError> {
770 let layers = vitrify_core::config::layers(repo_root, Some(home_dir))?;
771 harness::from_layers(&layers)
772}
773
774#[cfg(test)]
775mod tests {
776 use super::*;
777
778 const BLOCK: &str = "[probe]\nvitrify_version = \"1\"\n\n[probe.claude]\npresent = true\n";
779
780 #[test]
781 fn the_record_is_appended_when_there_is_none() {
782 let text = "schema = 1\n\n[run]\nworker_cap = 4 # mine\n";
783 let out = replace_record(text, BLOCK);
784 assert_eq!(out, format!("{text}\n{BLOCK}"));
785 assert_eq!(updated_text(text, BLOCK).unwrap(), out);
786 }
787
788 #[test]
789 fn only_the_record_is_replaced_in_place() {
790 let text = "# top\nschema = 1\n\n[run]\nworker_cap = 2 # mine\n\n[probe]\nvitrify_version = \"0\"\n\n[probe.codex]\npresent = false\n\n[lint]\n# keep\nreadset_budget_bytes = 9\n";
791 let out = updated_text(text, BLOCK).unwrap();
792 assert_eq!(
793 out,
794 "# top\nschema = 1\n\n[run]\nworker_cap = 2 # mine\n\n[probe]\nvitrify_version = \"1\"\n\n[probe.claude]\npresent = true\n\n[lint]\n# keep\nreadset_budget_bytes = 9\n"
795 );
796 }
797
798 #[test]
799 fn a_header_inside_a_multi_line_string_is_not_a_table() {
800 let text = "note = \"\"\"\n[probe]\n\"\"\"\n[run]\nworker_cap = 1\n";
801 let out = updated_text(text, BLOCK).unwrap();
802 assert!(out.starts_with(text), "{out}");
803 }
804
805 #[test]
806 fn changes_name_what_moved() {
807 let old: toml::Table = "[probe.claude]\npresent = true\nversion = \"1\"\n"
808 .parse()
809 .unwrap();
810 let new: toml::Table =
811 "[probe.claude]\npresent = true\nversion = \"2\"\nheadless = [\"claude\", \"-p\"]\n"
812 .parse()
813 .unwrap();
814 let lines: Vec<String> = changes(&flatten_record(&old), &flatten_record(&new))
815 .iter()
816 .map(Change::line)
817 .collect();
818 assert_eq!(
819 lines,
820 [
821 "probe.claude.headless: (none) → claude -p",
822 "probe.claude.version: 1 → 2"
823 ]
824 );
825 assert!(changes(&flatten_record(&new), &flatten_record(&new)).is_empty());
826 }
827
828 #[test]
829 fn strings_are_escaped() {
830 assert_eq!(toml_str("a\"b\\c"), "\"a\\\"b\\\\c\"");
831 }
832}