vpf-runner 0.4.0

The reference runner of the Verifiable Plan Format (VPF): runs a plan step by step and proves each step.
Documentation
//! The person: who answers a step by `person`, approves work, and decides when the run needs them.

use std::io::{BufRead, Write};

use serde::{Deserialize, Serialize};

/// What a person is asked.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Ask {
    /// The question, in words.
    pub question: String,
    /// The named people it is for, any of whom may answer. Empty when it is for the person who asked for the run.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub people: Vec<String>,
    /// The answers they may give, when the step has choices.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub choices: Vec<String>,
    /// The earlier steps a refusal may send the work back to, when the proof says.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub back_to: Vec<String>,
}

impl Ask {
    /// The question, with the people it is for when it is not for the person who asked for the run.
    pub fn addressed(&self) -> String {
        if self.people.is_empty() {
            self.question.clone()
        } else {
            format!("For {}: {}", self.people.join(" or "), self.question)
        }
    }
}

/// What the person said of the work.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Verdict {
    /// They approve.
    Yes,
    /// They do not.
    No {
        /// The points against the work.
        points: String,
        /// The earlier steps they send the work back to, among those offered. None sends it back to its own
        /// step.
        back: Vec<String>,
    },
}

/// The person the plan is for, and the people its steps name.
pub trait Person {
    /// Tells them what happens.
    fn tell(&mut self, text: &str);

    /// Asks for a text. `None` when they do not answer.
    fn answer(&mut self, ask: &Ask) -> Option<String>;

    /// Asks them to approve work. `None` when they do not answer.
    fn approve(&mut self, ask: &Ask) -> Option<Verdict>;

    /// Asks a yes or no question. `None` when they do not answer.
    fn decide(&mut self, question: &str) -> Option<bool> {
        let ask = Ask {
            question: question.to_owned(),
            ..Ask::default()
        };
        self.approve(&ask).map(|verdict| verdict == Verdict::Yes)
    }

    /// Asks them to choose one of the options. The one they chose, or `None` when they do not answer.
    fn choose(&mut self, question: &str, options: &[String]) -> Option<usize> {
        let ask = Ask {
            question: question.to_owned(),
            choices: options.to_vec(),
            ..Ask::default()
        };
        let answer = self.answer(&ask)?;
        options.iter().position(|option| *option == answer.trim())
    }
}

/// A person at a terminal: told on one stream and answering on another.
pub struct Terminal<R, W> {
    input: R,
    output: W,
}

impl<R: BufRead, W: Write> Terminal<R, W> {
    /// A person who answers from `input` and is told on `output`.
    pub fn new(input: R, output: W) -> Self {
        Self { input, output }
    }

    fn line(&mut self, prompt: &str) -> Option<String> {
        let _ = write!(self.output, "{prompt}");
        let _ = self.output.flush();
        let mut line = String::new();
        match self.input.read_line(&mut line) {
            Ok(0) | Err(_) => {
                let _ = writeln!(self.output);
                None
            }
            Ok(_) => Some(line.trim().to_owned()),
        }
    }

    fn yes_or_no(&mut self, question: &str) -> Option<bool> {
        let mut prompt = format!("{question} (yes/no) ");
        loop {
            let reply = self.line(&prompt)?.to_lowercase();
            match reply.as_str() {
                "y" | "yes" => return Some(true),
                "n" | "no" => return Some(false),
                _ => "Please answer yes or no: ".clone_into(&mut prompt),
            }
        }
    }
}

impl<R: BufRead, W: Write> Person for Terminal<R, W> {
    fn tell(&mut self, text: &str) {
        let _ = writeln!(self.output, "{text}");
    }

    fn answer(&mut self, ask: &Ask) -> Option<String> {
        if ask.choices.is_empty() {
            return self.line(&format!("{}\n> ", ask.addressed()));
        }
        let choices = ask.choices.join(", ");
        let mut prompt = format!("{}\nAnswer one of: {choices}\n> ", ask.addressed());
        loop {
            let reply = self.line(&prompt)?;
            if ask.choices.contains(&reply) {
                return Some(reply);
            }
            prompt = format!("Please answer one of: {choices}\n> ");
        }
    }

    fn approve(&mut self, ask: &Ask) -> Option<Verdict> {
        if self.yes_or_no(&ask.addressed())? {
            return Some(Verdict::Yes);
        }
        let points = self.line("What is wrong with it?\n> ").unwrap_or_default();
        let mut back = Vec::new();
        if !ask.back_to.is_empty() {
            let offered = ask.back_to.join(", ");
            let mut prompt =
                format!("Send it back to which step? ({offered}; leave empty for this one)\n> ");
            loop {
                let reply = self.line(&prompt).unwrap_or_default();
                let named: Vec<String> = reply
                    .split([',', ' '])
                    .map(str::trim)
                    .filter(|id| !id.is_empty())
                    .map(str::to_owned)
                    .collect();
                if named.iter().all(|id| ask.back_to.contains(id)) {
                    back = named;
                    break;
                }
                prompt = format!("Please name some of: {offered}, or leave it empty\n> ");
            }
        }
        Some(Verdict::No { points, back })
    }

    fn decide(&mut self, question: &str) -> Option<bool> {
        self.yes_or_no(question)
    }

    fn choose(&mut self, question: &str, options: &[String]) -> Option<usize> {
        let _ = writeln!(self.output, "{question}");
        for (number, option) in options.iter().enumerate() {
            let _ = writeln!(self.output, "  {}. {option}", number + 1);
        }
        let mut prompt = "> ".to_owned();
        loop {
            let reply = self.line(&prompt)?;
            let picked = reply
                .parse::<usize>()
                .ok()
                .and_then(|number| number.checked_sub(1))
                .filter(|index| *index < options.len())
                .or_else(|| options.iter().position(|option| *option == reply));
            if picked.is_some() {
                return picked;
            }
            prompt = format!("Please answer a number from 1 to {}: ", options.len());
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{Ask, Person, Terminal, Verdict};

    fn ask(question: &str) -> Ask {
        Ask {
            question: question.to_owned(),
            ..Ask::default()
        }
    }

    #[test]
    fn a_terminal_person_answers_by_lines() {
        let mut output = Vec::new();
        let mut person = Terminal::new("Ana\nmaybe\nno\ntoo short\nYES\n".as_bytes(), &mut output);

        assert_eq!(person.answer(&ask("Who?")).as_deref(), Some("Ana"));
        assert_eq!(
            person.approve(&ask("Good?")),
            Some(Verdict::No {
                points: "too short".to_owned(),
                back: Vec::new()
            })
        );
        assert_eq!(person.decide("Go on?"), Some(true));
        assert_eq!(person.decide("Again?"), None);
        let said = String::from_utf8(output).expect("text");
        assert!(said.contains("Please answer yes or no"), "{said}");
    }

    #[test]
    fn a_terminal_person_picks_and_sends_back() {
        let mut output = Vec::new();
        let input = "water\ntea\nno\nwrong\nnope\nintro, numbers\n2\n";
        let mut person = Terminal::new(input.as_bytes(), &mut output);
        let tea = Ask {
            question: "Which?".to_owned(),
            people: vec!["ana".to_owned(), "bo".to_owned()],
            choices: vec!["tea".to_owned(), "coffee".to_owned()],
            back_to: Vec::new(),
        };
        let report = Ask {
            back_to: vec!["intro".to_owned(), "numbers".to_owned()],
            ..ask("Right?")
        };

        assert_eq!(person.answer(&tea).as_deref(), Some("tea"));
        assert_eq!(
            person.approve(&report),
            Some(Verdict::No {
                points: "wrong".to_owned(),
                back: vec!["intro".to_owned(), "numbers".to_owned()]
            })
        );
        let options = ["wait".to_owned(), "go on".to_owned()];
        assert_eq!(person.choose("Now?", &options), Some(1));
        let said = String::from_utf8(output).expect("text");
        assert!(said.contains("For ana or bo: Which?"), "{said}");
        assert!(said.contains("Please answer one of: tea, coffee"), "{said}");
        assert!(
            said.contains("Please name some of: intro, numbers"),
            "{said}"
        );
    }
}