Skip to main content

vpf_runner/
record.rs

1//! What a runner keeps of a run: each step's answers, each proof with its result, the steps skipped, the
2//! person's decisions, each version of the plan, and what the run waits for, so it can go on later.
3
4use std::fs;
5use std::path::{Path, PathBuf};
6
7use jiff::Timestamp;
8use jiff::tz::TimeZone;
9use serde::{Deserialize, Serialize};
10use serde_json::{Value, json};
11use vpf::{Plan, Step};
12
13use crate::journal::Entry;
14use crate::person::Ask;
15
16/// How a run ended, or where it stands.
17#[derive(Clone, Debug, PartialEq, Eq)]
18pub enum Outcome {
19    /// The last step passed.
20    Done,
21    /// The run stopped, for this reason.
22    Stopped(String),
23    /// The run waits, holding nothing, for these answers and times. It goes on with [`crate::Runner::resume`].
24    Waiting(Vec<Waiting>),
25}
26
27/// One thing a waiting run waits for.
28#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
29pub struct Waiting {
30    /// The step that waits.
31    pub step: String,
32    /// What names the answer in the run, to give it with [`Record::reply`].
33    pub key: String,
34    /// What it waits for.
35    pub wait: Wait,
36}
37
38/// What a step waits for.
39#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
40#[serde(rename_all = "snake_case")]
41pub enum Wait {
42    /// A text: a person's step, or a name the plan's reference did not give.
43    Answer(Ask),
44    /// A person's approval of the work: yes, or no with the points against it.
45    Approval(Ask),
46    /// Yes or no.
47    Decision(String),
48    /// One of the options.
49    Choice {
50        /// The question.
51        question: String,
52        /// The options, in order.
53        options: Vec<String>,
54    },
55    /// A time: the step may not start before it.
56    Time(Timestamp),
57}
58
59/// A person's reply to what a run waits for.
60#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
61#[serde(rename_all = "snake_case")]
62pub enum Reply {
63    /// A text, for [`Wait::Answer`].
64    Text(String),
65    /// Yes, for [`Wait::Approval`] or [`Wait::Decision`].
66    Yes,
67    /// No, for [`Wait::Approval`] or [`Wait::Decision`].
68    No {
69        /// The points against the work.
70        points: String,
71        /// The earlier steps the work goes back to, among those offered.
72        back: Vec<String>,
73    },
74    /// The option chosen, counted from 0, for [`Wait::Choice`].
75    Option(usize),
76}
77
78/// One version of the plan a run followed.
79#[derive(Clone, Debug, PartialEq)]
80pub struct Version {
81    /// The plan.
82    pub plan: Plan,
83    /// Who approved it, for a version taken during the run.
84    pub approved_by: Option<String>,
85    /// The first step it was followed from, the first that had not ended.
86    pub from: Option<String>,
87    /// When it was taken.
88    pub at: Timestamp,
89}
90
91/// One proof asked, with its result. A skipped proof is kept without `passed`, since it neither passed nor refused.
92#[derive(Clone, Debug, Deserialize)]
93pub struct ProofRecord {
94    /// Who proved: `algorithm`, `agent` or `person`.
95    pub by: String,
96    /// What was asked: the command, the needs, the check or the question, with references filled.
97    pub asked: String,
98    /// Whether it passed. `false` for a skipped proof.
99    #[serde(default)]
100    pub passed: bool,
101    /// The points against the work, when it did not pass.
102    #[serde(default, skip_serializing_if = "Option::is_none")]
103    pub points: Option<String>,
104    /// Whether it was skipped: it is for another answer of a choice, so it was not asked and did not refuse.
105    #[serde(default)]
106    pub skipped: bool,
107    /// Why it was skipped: the answer it is for, and the answer given.
108    #[serde(default)]
109    pub reason: Option<String>,
110}
111
112impl Serialize for ProofRecord {
113    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
114        use serde::ser::SerializeMap;
115        let mut map = serializer.serialize_map(None)?;
116        map.serialize_entry("by", &self.by)?;
117        map.serialize_entry("asked", &self.asked)?;
118        if self.skipped {
119            map.serialize_entry("skipped", &true)?;
120        } else {
121            map.serialize_entry("passed", &self.passed)?;
122        }
123        if let Some(points) = &self.points {
124            map.serialize_entry("points", points)?;
125        }
126        if let Some(reason) = &self.reason {
127            map.serialize_entry("reason", reason)?;
128        }
129        map.end()
130    }
131}
132
133/// One try at a step's work.
134#[derive(Clone, Debug, Serialize, Deserialize)]
135pub struct Attempt {
136    /// Who did the work: `agent`, `algorithm`, `person` or `plan`.
137    pub by: String,
138    /// What they answered.
139    #[serde(default, skip_serializing_if = "Option::is_none")]
140    pub answer: Option<String>,
141    /// The proofs asked, in order, up to the first that refused.
142    pub proofs: Vec<ProofRecord>,
143    /// The steps of the other plan, for a step by `plan`.
144    #[serde(default, skip_serializing_if = "Vec::is_empty")]
145    pub steps: Vec<StepRecord>,
146    /// The earlier steps a refusal sent the work back to, when it named some.
147    #[serde(default, skip_serializing_if = "Vec::is_empty")]
148    pub back: Vec<String>,
149    /// Why the work failed before any proof was asked: its agent ended with an error, or it cannot be undone and
150    /// was not done when the run stopped.
151    #[serde(default, skip_serializing_if = "Option::is_none")]
152    pub failed: Option<String>,
153    /// The conversation the agent did the work in, when it said.
154    #[serde(default, skip_serializing_if = "Option::is_none")]
155    pub conversation: Option<String>,
156    /// The files added, changed or removed in the folder from when the work began to when it ended, in order,
157    /// when the runner saw both. Work done at the same time by other steps shows here too.
158    #[serde(default, skip_serializing_if = "Vec::is_empty")]
159    pub changed: Vec<String>,
160}
161
162impl Attempt {
163    /// A try by `by`, with nothing done yet.
164    pub fn by(by: &str) -> Self {
165        Self {
166            by: by.to_owned(),
167            answer: None,
168            proofs: Vec::new(),
169            steps: Vec::new(),
170            back: Vec::new(),
171            failed: None,
172            conversation: None,
173            changed: Vec::new(),
174        }
175    }
176}
177
178/// One item of a step done for each item.
179#[derive(Clone, Debug, Serialize, Deserialize)]
180pub struct ItemRecord {
181    /// The item, as `{{item}}` names it.
182    pub item: String,
183    /// Its answer, once it passed.
184    pub answer: Option<String>,
185    /// Each try at its work.
186    pub attempts: Vec<Attempt>,
187}
188
189/// One step of the run.
190#[derive(Clone, Debug, Serialize, Deserialize)]
191pub struct StepRecord {
192    /// The step's id.
193    pub id: String,
194    /// Its answer, once it passed.
195    pub answer: Option<String>,
196    /// Whether it was skipped: its path was not taken, or the person went on without it.
197    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
198    pub skipped: bool,
199    /// Whether it has ended, passed or skipped, and is not to be done again.
200    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
201    pub ended: bool,
202    /// Each try at its work. Work sent back to it adds more.
203    pub attempts: Vec<Attempt>,
204    /// Each item, for a step done for each item.
205    #[serde(default, skip_serializing_if = "Vec::is_empty")]
206    pub items: Vec<ItemRecord>,
207}
208
209impl StepRecord {
210    /// A step not started yet.
211    pub fn new(id: &str) -> Self {
212        Self {
213            id: id.to_owned(),
214            answer: None,
215            skipped: false,
216            ended: false,
217            attempts: Vec::new(),
218            items: Vec::new(),
219        }
220    }
221
222    /// Whether its work has started.
223    pub fn started(&self) -> bool {
224        !self.attempts.is_empty() || !self.items.is_empty()
225    }
226}
227
228/// A question the person decided.
229#[derive(Clone, Debug, Serialize, Deserialize)]
230pub struct Decision {
231    /// The step it was about.
232    pub step: String,
233    /// What they were asked.
234    pub asked: String,
235    /// What they answered: `yes`, `no`, the option they chose, or `none`.
236    pub answer: String,
237    /// Who answered, when someone answered from elsewhere and said who they are.
238    #[serde(default, skip_serializing_if = "Option::is_none")]
239    pub by: Option<String>,
240}
241
242/// One run of a plan.
243#[derive(Clone, Debug)]
244pub struct Record {
245    /// What names the run: when it started and the plan's name. Its file in `.vpf/runs` is `{id}.json`.
246    pub id: String,
247    /// The plan's name, when it has one.
248    pub plan: Option<String>,
249    /// The plan's wish.
250    pub wish: String,
251    /// What the run was started with.
252    pub asked: String,
253    /// When it started.
254    pub started: Timestamp,
255    /// When it ended, or last stopped to wait.
256    pub ended: Timestamp,
257    /// How it ended, or what it waits for.
258    pub outcome: Outcome,
259    /// What the agents said it cost.
260    pub cost: f64,
261    /// Whether some agent did not say what it cost.
262    pub cost_unmeasured: bool,
263    /// Every step of the plan, in the order written.
264    pub steps: Vec<StepRecord>,
265    /// What the person decided.
266    pub decisions: Vec<Decision>,
267    /// Each version of the plan the run followed, the first first.
268    pub versions: Vec<Version>,
269    /// Everything the run was given from outside it, by agents, commands, people and the clock, so that it can go
270    /// on from where it stands without asking any of it again.
271    pub journal: Vec<Entry>,
272}
273
274/// A record as kept in its file.
275#[derive(Deserialize)]
276struct Kept {
277    #[serde(default)]
278    id: String,
279    plan: Option<String>,
280    wish: String,
281    asked: String,
282    started: Timestamp,
283    ended: Timestamp,
284    outcome: String,
285    #[serde(default)]
286    reason: Option<String>,
287    #[serde(default)]
288    waiting: Option<Vec<Waiting>>,
289    cost: f64,
290    cost_unmeasured: bool,
291    steps: Vec<StepRecord>,
292    decisions: Vec<Decision>,
293    #[serde(default)]
294    versions: Vec<KeptVersion>,
295    #[serde(default)]
296    journal: Vec<Entry>,
297}
298
299#[derive(Deserialize)]
300struct KeptVersion {
301    plan: Value,
302    approved_by: Option<String>,
303    from: Option<String>,
304    at: Timestamp,
305}
306
307impl Record {
308    /// The record as JSON.
309    pub fn to_json(&self) -> Value {
310        let (outcome, reason, waiting) = match &self.outcome {
311            Outcome::Done => ("done", None, None),
312            Outcome::Stopped(reason) => ("stopped", Some(reason), None),
313            Outcome::Waiting(waiting) => ("waiting", None, Some(waiting)),
314        };
315        let versions: Vec<Value> = self
316            .versions
317            .iter()
318            .map(|version| {
319                json!({
320                    "plan": version.plan,
321                    "approved_by": version.approved_by,
322                    "from": version.from,
323                    "at": version.at,
324                })
325            })
326            .collect();
327        json!({
328            "id": self.id,
329            "plan": self.plan,
330            "wish": self.wish,
331            "asked": self.asked,
332            "started": self.started.to_string(),
333            "ended": self.ended.to_string(),
334            "outcome": outcome,
335            "reason": reason,
336            "waiting": waiting,
337            "cost": self.cost,
338            "cost_unmeasured": self.cost_unmeasured,
339            "steps": self.steps,
340            "decisions": self.decisions,
341            "versions": versions,
342            "journal": self.journal,
343        })
344    }
345
346    /// Reads a record kept in a file.
347    ///
348    /// # Errors
349    ///
350    /// When the file cannot be read, or does not hold a record.
351    pub fn load(file: &Path) -> Result<Self, String> {
352        let text = fs::read_to_string(file)
353            .map_err(|error| format!("cannot read {}: {error}", file.display()))?;
354        let kept: Kept = serde_json::from_str(&text)
355            .map_err(|error| format!("{} does not hold a run: {error}", file.display()))?;
356        let outcome = match kept.outcome.as_str() {
357            "done" => Outcome::Done,
358            "waiting" => Outcome::Waiting(kept.waiting.unwrap_or_default()),
359            _ => Outcome::Stopped(kept.reason.unwrap_or_default()),
360        };
361        let mut versions = Vec::new();
362        for version in kept.versions {
363            let report = vpf::check(&version.plan.to_string());
364            let plan = report
365                .plan
366                .filter(|_| report.problems.is_empty())
367                .ok_or_else(|| format!("{} holds a plan with problems", file.display()))?;
368            versions.push(Version {
369                plan,
370                approved_by: version.approved_by,
371                from: version.from,
372                at: version.at,
373            });
374        }
375        let id = if kept.id.is_empty() {
376            file.file_stem()
377                .and_then(|stem| stem.to_str())
378                .unwrap_or_default()
379                .to_owned()
380        } else {
381            kept.id
382        };
383        Ok(Self {
384            id,
385            plan: kept.plan,
386            wish: kept.wish,
387            asked: kept.asked,
388            started: kept.started,
389            ended: kept.ended,
390            outcome,
391            cost: kept.cost,
392            cost_unmeasured: kept.cost_unmeasured,
393            steps: kept.steps,
394            decisions: kept.decisions,
395            versions,
396            journal: kept.journal,
397        })
398    }
399
400    /// Where the record is kept in the folder.
401    pub fn file(&self, folder: &Path) -> PathBuf {
402        runs(folder).join(format!("{}.json", self.id))
403    }
404
405    /// Writes the record in the folder's `.vpf/runs`, in place of what it kept of the run before.
406    ///
407    /// # Errors
408    ///
409    /// When the file cannot be written.
410    pub fn keep(&self, folder: &Path) -> std::io::Result<PathBuf> {
411        fs::create_dir_all(runs(folder))?;
412        let file = self.file(folder);
413        let text = serde_json::to_string_pretty(&self.to_json()).unwrap_or_default();
414        fs::write(&file, text + "\n")?;
415        Ok(file)
416    }
417
418    /// Adds entries a [`Keeper`](crate::Keeper) was handed to the run's journal, in order: an entry under a key
419    /// the journal holds takes the place of the one there. A run that stopped in the middle is rebuilt this way
420    /// from the record it began with, and goes on without asking any of them again.
421    pub fn add_entries(&mut self, entries: impl IntoIterator<Item = Entry>) {
422        let mut places: std::collections::HashMap<String, usize> = self
423            .journal
424            .iter()
425            .enumerate()
426            .map(|(place, entry)| (entry.key.clone(), place))
427            .collect();
428        for entry in entries {
429            if let Some(&place) = places.get(&entry.key) {
430                self.journal[place] = entry;
431            } else {
432                places.insert(entry.key.clone(), self.journal.len());
433                self.journal.push(entry);
434            }
435        }
436    }
437
438    /// Gives a waiting run the reply to what it waits for under `key`, from `by` when they say who they are. The
439    /// run goes on with it when it is resumed.
440    ///
441    /// # Errors
442    ///
443    /// When the run does not wait for `key`, the reply does not fit what is asked, or the question is for named
444    /// people and `by` is not one of them.
445    pub fn reply(&mut self, key: &str, reply: Reply, by: Option<&str>) -> Result<(), String> {
446        let Outcome::Waiting(waiting) = &mut self.outcome else {
447            return Err(format!("the run {} waits for nothing", self.id));
448        };
449        let place = waiting
450            .iter()
451            .position(|waiting| waiting.key == key)
452            .ok_or_else(|| format!("the run {} does not wait for {key}", self.id))?;
453        fits(&waiting[place].wait, &reply, by)?;
454        waiting.remove(place);
455        self.journal.push(Entry {
456            key: key.to_owned(),
457            at: Timestamp::now(),
458            by: by.map(str::to_owned),
459            value: serde_json::to_value(reply).unwrap_or_default(),
460        });
461        Ok(())
462    }
463
464    /// Takes a new version of the plan for a waiting run, approved by `approved_by`: the run goes on with it from
465    /// where it stands when it is resumed.
466    ///
467    /// # Errors
468    ///
469    /// When the run does not wait, no one approved, the plan has problems, a step that ended is not in it as it
470    /// was, or a step that started is not in it with the same `id`, `by` and `do`.
471    pub fn change(&mut self, plan: &Plan, approved_by: &str, at: Timestamp) -> Result<(), String> {
472        if !matches!(self.outcome, Outcome::Waiting(_)) {
473            return Err(format!(
474                "the run {} does not wait, so its plan cannot change",
475                self.id
476            ));
477        }
478        let approved_by = approved_by.trim();
479        if approved_by.is_empty() {
480            return Err("a new version of the plan needs the person's approval".to_owned());
481        }
482        let report = vpf::check(&serde_json::to_string(plan).unwrap_or_default());
483        if !report.problems.is_empty() {
484            let problems: Vec<String> = report.problems.iter().map(ToString::to_string).collect();
485            return Err(format!(
486                "the new version has problems: {}",
487                problems.join("; ")
488            ));
489        }
490        let old = self
491            .versions
492            .last()
493            .ok_or_else(|| format!("the run {} keeps no plan", self.id))?;
494        for (step, record) in old.plan.steps.iter().zip(&self.steps) {
495            let new = plan.steps.iter().find(|new| new.id == step.id);
496            if record.ended && new != Some(step) {
497                return Err(format!(
498                    "the step {} has ended, so it must stay as it was",
499                    step.id
500                ));
501            }
502            if record.started()
503                && !new.is_some_and(|new| new.by == step.by && new.what == step.what)
504            {
505                return Err(format!(
506                    "the step {} has started, so it must keep its id, by and do",
507                    step.id
508                ));
509            }
510            if record.started() && step.irreversible() && !new.is_some_and(Step::irreversible) {
511                return Err(format!(
512                    "the step {} has started and cannot be undone, so it stays so",
513                    step.id
514                ));
515            }
516        }
517        let ended: Vec<&str> = self
518            .steps
519            .iter()
520            .filter(|record| record.ended)
521            .map(|record| record.id.as_str())
522            .collect();
523        let from = plan
524            .steps
525            .iter()
526            .find(|step| !ended.contains(&step.id.as_str()))
527            .map(|step| step.id.clone());
528        self.wish = crate::fill::fill(
529            &plan.wish,
530            &std::collections::HashMap::from([("asked".to_owned(), self.asked.clone())]),
531        );
532        self.versions.push(Version {
533            plan: plan.clone(),
534            approved_by: Some(approved_by.to_owned()),
535            from,
536            at,
537        });
538        Ok(())
539    }
540}
541
542/// Whether a reply fits what is waited for, and comes from someone it is for.
543fn fits(wait: &Wait, reply: &Reply, by: Option<&str>) -> Result<(), String> {
544    let ask = match wait {
545        Wait::Answer(ask) | Wait::Approval(ask) => Some(ask),
546        _ => None,
547    };
548    if let Some(ask) = ask.filter(|ask| !ask.people.is_empty()) {
549        if !by.is_some_and(|by| ask.people.iter().any(|person| person == by)) {
550            return Err(format!(
551                "only {} may answer this; say who answers",
552                ask.people.join(" or ")
553            ));
554        }
555    }
556    match (wait, reply) {
557        (Wait::Answer(ask), Reply::Text(text)) => {
558            if ask.choices.is_empty() || ask.choices.iter().any(|choice| choice == text.trim()) {
559                Ok(())
560            } else {
561                Err(format!(
562                    "the answer must be one of: {}",
563                    ask.choices.join(", ")
564                ))
565            }
566        }
567        (Wait::Approval(ask), Reply::No { back, .. }) => {
568            match back.iter().find(|id| !ask.back_to.contains(id)) {
569                Some(id) => Err(format!(
570                    "the work may not go back to {id}; it may go back to: {}",
571                    ask.back_to.join(", ")
572                )),
573                None => Ok(()),
574            }
575        }
576        (Wait::Approval(_) | Wait::Decision(_), Reply::Yes)
577        | (Wait::Decision(_), Reply::No { .. }) => Ok(()),
578        (Wait::Choice { options, .. }, Reply::Option(chosen)) if *chosen < options.len() => Ok(()),
579        (Wait::Time(at), _) => Err(format!("this waits for a time, {at}, not for an answer")),
580        _ => Err("the reply does not fit what is asked".to_owned()),
581    }
582}
583
584/// Where a folder keeps its runs.
585pub fn runs(folder: &Path) -> PathBuf {
586    folder.join(".vpf").join("runs")
587}
588
589/// What the runs of a plan kept in the folder cost in the calendar month of `now`, where the runner runs.
590pub fn spent_this_month(folder: &Path, plan: &str, now: Timestamp) -> f64 {
591    let zone = TimeZone::system();
592    let month = |at: Timestamp| {
593        let date = at.to_zoned(zone.clone()).date();
594        (date.year(), date.month())
595    };
596    let this = month(now);
597    let Ok(read) = fs::read_dir(runs(folder)) else {
598        return 0.0;
599    };
600    read.filter_map(Result::ok)
601        .filter_map(|entry| fs::read_to_string(entry.path()).ok())
602        .filter_map(|text| serde_json::from_str::<Value>(&text).ok())
603        .filter(|record| record["plan"] == plan)
604        .filter(|record| {
605            record["started"]
606                .as_str()
607                .and_then(|started| started.parse::<Timestamp>().ok())
608                .is_some_and(|started| month(started) == this)
609        })
610        .filter_map(|record| record["cost"].as_f64())
611        .sum()
612}