Skip to main content

vpf_runner/
run.rs

1//! A run: each step starts when the steps it waits for are done and its time has come, and passes when its
2//! proofs pass. A run that waits holds nothing: it keeps what it was given in its journal, and goes on from there.
3
4use std::collections::{HashMap, HashSet};
5use std::fmt::Write as _;
6use std::fs;
7use std::path::{Path, PathBuf};
8use std::sync::mpsc;
9use std::thread;
10use std::time::{Duration, Instant};
11
12use jiff::Timestamp;
13use serde::Serialize;
14use serde::de::DeserializeOwned;
15use vpf::{By, OnFail, Plan, Proof, Prover, Step, Tool};
16
17use crate::agent::{Agent, AgentAnswer, AgentRequest, Role};
18use crate::command::{self, TimeOver};
19use crate::fill::{fill, text};
20use crate::folder;
21use crate::journal::{Entry, Journal, Keeper, stamp};
22use crate::needs::{describe, meets};
23use crate::person::Person;
24use crate::person::{Ask, Verdict};
25use crate::record::{
26    Attempt, Decision, ItemRecord, Outcome, ProofRecord, Record, Reply, StepRecord, Version, Wait,
27    Waiting, runs, spent_this_month,
28};
29use crate::time::{Clock, Moment, SystemClock, words};
30
31const ALL_TOOLS: [&str; 5] = ["read", "write", "commands", "internet", "screen"];
32
33/// Before a step is done for more items than this, the person is asked.
34const MANY_ITEMS: usize = 200;
35
36/// How many agents and commands work at once, unless the runner is told otherwise.
37const AT_ONCE: usize = 8;
38
39/// What the person may do when a step passes its deadline.
40const LATE: [&str; 3] = [
41    "wait until a later deadline",
42    "go on without it",
43    "stop the run",
44];
45
46fn tool_name(tool: Tool) -> &'static str {
47    match tool {
48        Tool::Read => "read",
49        Tool::Write => "write",
50        Tool::Commands => "commands",
51        Tool::Internet => "internet",
52        Tool::Screen => "screen",
53    }
54}
55
56fn by_name(by: By) -> &'static str {
57    match by {
58        By::Agent => "agent",
59        By::Algorithm => "algorithm",
60        By::Person => "person",
61        By::Plan => "plan",
62    }
63}
64
65fn prover_name(by: Prover) -> &'static str {
66    match by {
67        Prover::Algorithm => "algorithm",
68        Prover::Agent => "agent",
69        Prover::Person => "person",
70    }
71}
72
73/// Why a run does not go on now.
74#[derive(Debug)]
75enum Halt {
76    /// It stops, for this reason.
77    Stop(String),
78    /// It waits for what the runner keeps in its list of what is waited for.
79    Pause,
80    /// The work it asked for failed, with these points against it: its agent ended with an error, or it cannot be
81    /// undone and was not done when the run stopped. The work is refused with them; out of such work, the run stops.
82    Failed(String),
83}
84
85impl Halt {
86    /// The halt out of any work: an agent's error stops the run.
87    fn out_of_work(self) -> Self {
88        match self {
89            Self::Failed(why) => Self::Stop(why),
90            other => other,
91        }
92    }
93}
94
95/// How the points against work begin when its agent ended with an error.
96const AGENT_ERROR: &str = "The agent ended with an error: ";
97
98/// The points against work that cannot be undone, when the person says it was not done before the run stopped.
99const NOT_DONE: &str =
100    "The run stopped before this work ended, and the person said it was not done.";
101
102/// Where work that cannot be undone stands as an attempt begins.
103#[derive(Clone, Debug, PartialEq, Eq)]
104enum Out {
105    /// It is to be done, or is being done now.
106    Fresh,
107    /// The run stopped while it was out, and the person said it was done, and what it answered.
108    Done(String),
109    /// The run stopped while it was out, and the person said it was not done.
110    NotDone,
111    /// The person did not start it, and sent the work back to these earlier steps, with these points.
112    Back(Vec<String>, String),
113}
114
115impl From<String> for Halt {
116    fn from(reason: String) -> Self {
117        Self::Stop(reason)
118    }
119}
120
121/// The texts references name: `asked`, the answers of the steps done, and `item`.
122type Values = HashMap<String, String>;
123
124/// Where a step stands in a run.
125#[derive(Clone, Copy, Debug, PartialEq, Eq)]
126enum State {
127    /// Not done: waiting, or to be done again.
128    Open,
129    /// Its work is done and every proof passed.
130    Passed,
131    /// Not on the path taken, or left out by the person.
132    Skipped,
133    /// Started, and waiting for an answer: the steps that wait for it wait too.
134    Parked,
135}
136
137impl State {
138    fn ended(self) -> bool {
139        matches!(self, Self::Passed | Self::Skipped)
140    }
141}
142
143/// What the run knows of one step.
144#[derive(Clone, Debug)]
145struct Progress {
146    state: State,
147    answer: String,
148    done: Option<Timestamp>,
149    /// Refused attempts since the person last said to go on.
150    refused: u32,
151    /// The last answer and the points against it, when its work was sent back.
152    again: Option<(String, String)>,
153    /// How many times it has started.
154    rounds: u32,
155}
156
157impl Default for Progress {
158    fn default() -> Self {
159        Self {
160            state: State::Open,
161            answer: String::new(),
162            done: None,
163            refused: 0,
164            again: None,
165            rounds: 0,
166        }
167    }
168}
169
170/// How a step's work ended.
171enum Ended {
172    Passed(String),
173    /// The person went on without it.
174    LeftOut,
175    /// A proof refused it and sent the work back to these earlier steps.
176    Back {
177        to: Vec<String>,
178        points: String,
179    },
180}
181
182/// Runs plans in a folder, with an agent and a person.
183pub struct Runner<'a> {
184    folder: PathBuf,
185    plans: PathBuf,
186    agent: &'a dyn Agent,
187    person: &'a mut dyn Person,
188    clock: Box<dyn Clock + 'a>,
189    time_cap: Option<Duration>,
190    name: Option<String>,
191    detach: bool,
192    at_once: usize,
193    // What one run has used so far.
194    end: Option<Timestamp>,
195    repeats: u32,
196    cost: f64,
197    cost_limit: Option<f64>,
198    unmeasured: bool,
199    told_unmeasured: bool,
200    decisions: Vec<Decision>,
201    stack: Vec<String>,
202    journal: Journal,
203    waiting: Vec<Waiting>,
204    /// What the person is told while the run goes over what it was given before, told once it goes past it.
205    held: Vec<String>,
206    /// The agents and commands the run would ask now, to be started.
207    jobs: Vec<(String, Job)>,
208    /// The keys of the agents and commands working now.
209    working: HashSet<String>,
210    /// The keys of the agents and commands asked in this session, working or waiting for their turn.
211    asked: HashSet<String>,
212    /// Why agents and commands that ended could not answer, by key.
213    failures: HashMap<String, String>,
214    /// The soonest time a step waits for, and the step.
215    soonest: Option<(Timestamp, String)>,
216    /// The folder as it was when each attempt began its work, by the attempt's key, to tell its proofs what changed.
217    before: HashMap<String, folder::Snapshot>,
218    /// The record of the run as it started, kept again while work that cannot be undone is out.
219    draft: Option<Record>,
220    /// The work that cannot be undone that is out now: the question a run that stopped meanwhile asks of each.
221    out: Vec<Waiting>,
222    /// Who is handed each entry as it is kept.
223    keeper: Option<&'a mut dyn Keeper>,
224    /// The entries the run holds that were handed out, or that it was given, by key.
225    handed: HashMap<String, Entry>,
226}
227
228impl<'a> Runner<'a> {
229    /// A runner for plans that work in `folder`, finding other plans by name in the same folder.
230    pub fn new(folder: &Path, agent: &'a dyn Agent, person: &'a mut dyn Person) -> Self {
231        Self {
232            folder: folder.to_owned(),
233            plans: folder.to_owned(),
234            agent,
235            person,
236            clock: Box::new(SystemClock),
237            time_cap: None,
238            name: None,
239            detach: false,
240            at_once: AT_ONCE,
241            end: None,
242            repeats: 3,
243            cost: 0.0,
244            cost_limit: None,
245            unmeasured: false,
246            told_unmeasured: false,
247            decisions: Vec::new(),
248            stack: Vec::new(),
249            journal: Journal::default(),
250            waiting: Vec::new(),
251            held: Vec::new(),
252            jobs: Vec::new(),
253            working: HashSet::new(),
254            asked: HashSet::new(),
255            failures: HashMap::new(),
256            soonest: None,
257            before: HashMap::new(),
258            draft: None,
259            out: Vec::new(),
260            keeper: None,
261            handed: HashMap::new(),
262        }
263    }
264
265    /// Finds the plans that steps name in this folder, `name.vpf.json`.
266    pub fn plans_in(&mut self, plans: &Path) -> &mut Self {
267        plans.clone_into(&mut self.plans);
268        self
269    }
270
271    /// Ends each run within this time, even when its plan allows more. A run that goes on later has this time
272    /// again.
273    pub fn time_limit(&mut self, limit: Duration) -> &mut Self {
274        self.time_cap = Some(limit);
275        self
276    }
277
278    /// Reads and waits on this clock instead of the computer's.
279    pub fn clock(&mut self, clock: Box<dyn Clock + 'a>) -> &mut Self {
280        self.clock = clock;
281        self
282    }
283
284    /// Keeps a record of each run in the folder's `.vpf/runs`, under the plan's name, and keeps to the plan's
285    /// `limits.month` across them.
286    pub fn keep_records(&mut self, name: &str) -> &mut Self {
287        self.name = Some(name.to_owned());
288        self
289    }
290
291    /// Asks no one and waits for no time: whatever a run would ask a person, and any time it would wait for,
292    /// leaves it waiting, holding nothing, while the steps that do not wait for it go on.
293    pub fn detach(&mut self, detach: bool) -> &mut Self {
294        self.detach = detach;
295        self
296    }
297
298    /// Has no more than this many agents and commands work at once, 8 when not told. Steps that wait for none
299    /// of each other, and the items of a step, are done at the same time up to it.
300    pub fn at_once(&mut self, most: usize) -> &mut Self {
301        self.at_once = most.max(1);
302        self
303    }
304
305    /// Hands each entry a run keeps to `keeper` as soon as it is kept, and tells it each record a run begins with,
306    /// so that a host keeps the run in its own store.
307    pub fn keeper(&mut self, keeper: &'a mut dyn Keeper) -> &mut Self {
308        self.keeper = Some(keeper);
309        self
310    }
311
312    /// Runs a plan that has no problems, started with `asked`.
313    pub fn run(&mut self, plan: &Plan, asked: &str) -> Record {
314        let started = self.clock.now();
315        let id = self.new_id(started);
316        let version = Version {
317            plan: plan.clone(),
318            approved_by: None,
319            from: None,
320            at: started,
321        };
322        self.go(id, vec![version], asked, started, Vec::new())
323    }
324
325    /// Goes on with a run from its record: from where it stands, with the replies it was given since and the
326    /// last version of its plan, asking nothing again that it was given before.
327    pub fn resume(&mut self, record: &Record) -> Record {
328        if record.versions.is_empty() {
329            let mut record = record.clone();
330            record.outcome = Outcome::Stopped(
331                "the run keeps no version of its plan, so it cannot go on".to_owned(),
332            );
333            return record;
334        }
335        self.name.clone_from(&record.plan);
336        self.go(
337            record.id.clone(),
338            record.versions.clone(),
339            &record.asked,
340            record.started,
341            record.journal.clone(),
342        )
343    }
344
345    /// A new run's id: when it started and the plan's name, not yet kept in the folder.
346    fn new_id(&self, started: Timestamp) -> String {
347        let stamp = started.to_string().replace(':', "-");
348        let name = self.name.as_deref().unwrap_or("plan");
349        let mut id = format!("{stamp}-{name}");
350        let mut count = 1;
351        while self.name.is_some() && runs(&self.folder).join(format!("{id}.json")).exists() {
352            count += 1;
353            id = format!("{stamp}-{name}-{count}");
354        }
355        id
356    }
357
358    fn go(
359        &mut self,
360        id: String,
361        versions: Vec<Version>,
362        asked: &str,
363        started: Timestamp,
364        journal: Vec<Entry>,
365    ) -> Record {
366        let plan = versions
367            .last()
368            .map(|version| version.plan.clone())
369            .expect("a run has a plan");
370        let fresh = journal.is_empty();
371        let limits = plan.limits();
372        self.end = limits
373            .deadline
374            .as_deref()
375            .and_then(Moment::read)
376            .map(|deadline| deadline.from(started));
377        if let Some(cap) = self.time_cap {
378            let cap = self
379                .clock
380                .now()
381                .saturating_add(
382                    jiff::SignedDuration::try_from(cap).unwrap_or(jiff::SignedDuration::MAX),
383                )
384                .unwrap_or(Timestamp::MAX);
385            self.end = Some(self.end.map_or(cap, |end| end.min(cap)));
386        }
387        self.repeats = limits.repeats.unwrap_or(3).max(1);
388        self.cost = 0.0;
389        self.cost_limit = limits.cost;
390        self.unmeasured = false;
391        self.told_unmeasured = false;
392        self.held = Vec::new();
393        self.failures = HashMap::new();
394        self.asked = HashSet::new();
395
396        let draft = Record {
397            id,
398            plan: self.name.clone(),
399            wish: fill(
400                &plan.wish,
401                &Values::from([("asked".to_owned(), asked.to_owned())]),
402            ),
403            asked: asked.to_owned(),
404            started,
405            ended: started,
406            outcome: Outcome::Waiting(Vec::new()),
407            cost: 0.0,
408            cost_unmeasured: false,
409            steps: Vec::new(),
410            decisions: Vec::new(),
411            versions,
412            journal: Vec::new(),
413        };
414        self.draft = self.name.is_some().then(|| draft.clone());
415        self.handed = journal
416            .iter()
417            .map(|entry| (entry.key.clone(), entry.clone()))
418            .collect();
419        if let Some(keeper) = self.keeper.as_deref_mut() {
420            let mut begun = draft.clone();
421            begun.journal.clone_from(&journal);
422            keeper.begin(&begun);
423        }
424
425        let spent = match (&self.name, limits.month) {
426            (Some(name), Some(_)) if fresh => spent_this_month(&self.folder, name, started),
427            _ => 0.0,
428        };
429        let (ended, steps) = match limits.month {
430            Some(month) if spent >= month => {
431                self.journal = Journal::new(journal, started);
432                let reason = format!(
433                    "this month's runs of the plan have spent {spent}, which reaches its limit of {month} for the month"
434                );
435                (Err(Halt::Stop(reason)), Vec::new())
436            }
437            _ => self.waves(&plan, asked, started, journal),
438        };
439        self.told();
440        let outcome = match ended {
441            Ok(_) => Outcome::Done,
442            Err(Halt::Stop(reason)) => Outcome::Stopped(reason),
443            Err(Halt::Failed(why)) => Outcome::Stopped(why),
444            Err(Halt::Pause) => Outcome::Waiting(std::mem::take(&mut self.waiting)),
445        };
446        let journal = self.journal.entries();
447        let record = self.as_it_stands(draft, outcome, steps, journal);
448        if let Some(name) = self.name.clone() {
449            if let Err(error) = record.keep(&self.folder) {
450                self.person.tell(&format!(
451                    "The record of this run could not be kept: {error}"
452                ));
453            } else {
454                // How work that cannot be undone ended is in the record now.
455                let _ = fs::remove_dir_all(runs(&self.folder).join(format!("{}.out", record.id)));
456            }
457            if let Some(month) = limits.month {
458                let total = spent_this_month(&self.folder, &name, started);
459                if total >= month * 0.8 {
460                    self.person.tell(&format!(
461                        "The runs of this plan have spent {total} of its {month} for the month: four fifths or more."
462                    ));
463                }
464            }
465        }
466        record
467    }
468
469    /// Goes over the run again and again, from the start, with what it was given so far, until it ends or waits for
470    /// people or a time: each time over, it starts the agents and commands the steps would ask now, at once, and
471    /// goes over it again when one of them answers.
472    fn waves(
473        &mut self,
474        plan: &Plan,
475        asked: &str,
476        started: Timestamp,
477        mut entries: Vec<Entry>,
478    ) -> (Result<String, Halt>, Vec<StepRecord>) {
479        let agent = self.agent;
480        let folder = self.folder.clone();
481        thread::scope(|scope| {
482            let (send, receive) = mpsc::channel::<(String, Finished)>();
483            // The guard of each agent that may only read and works now, and the folder before they began.
484            let mut readers: HashMap<String, String> = HashMap::new();
485            let mut before: Option<u64> = None;
486            // Whether work that cannot be undone was out when the run went over it last.
487            let mut was_out = false;
488            loop {
489                self.journal = Journal::new(entries.clone(), started);
490                self.cost = 0.0;
491                self.unmeasured = false;
492                self.decisions = Vec::new();
493                self.stack = self.name.iter().cloned().collect();
494                self.waiting = Vec::new();
495                self.jobs = Vec::new();
496                self.soonest = None;
497                self.out = Vec::new();
498                let mut steps = Vec::new();
499                let ended = self
500                    .steps(plan, asked, &mut steps, "")
501                    .map_err(Halt::out_of_work);
502                entries = self.journal.entries();
503                // Whenever the run was given something new, while work that cannot be undone is out, and once more
504                // when it ends, the record is kept, so that a run that stops meanwhile goes on from there, and asks
505                // whether work that cannot be undone was done instead of doing it again.
506                let given = self.hand_out(&entries);
507                if given || was_out || !self.out.is_empty() {
508                    self.keep_meanwhile(&steps, &entries);
509                }
510                was_out = !self.out.is_empty();
511
512                if !matches!(ended, Err(Halt::Stop(_))) {
513                    for (key, job) in std::mem::take(&mut self.jobs) {
514                        if self.working.len() >= self.at_once || self.working.contains(&key) {
515                            continue;
516                        }
517                        let guard = job.guard();
518                        // An agent that may only read works only while nothing writes, so that what it changes
519                        // is known to be its own.
520                        let writing = self.working.len() > readers.len();
521                        if guard.is_some() && writing || guard.is_none() && !readers.is_empty() {
522                            continue;
523                        }
524                        if let Some(guard) = guard {
525                            if readers.is_empty() {
526                                before = Some(folder::digest(&folder));
527                            }
528                            readers.insert(key.clone(), guard.to_owned());
529                        }
530                        self.working.insert(key.clone());
531                        let send = send.clone();
532                        let deadline = self.instant();
533                        let cost_left = self
534                            .cost_limit
535                            .filter(|_| !self.unmeasured)
536                            .map(|limit| (limit - self.cost).max(0.0));
537                        // An agent of a run kept in the folder keeps its work there, to be found again.
538                        let keep = matches!(job, Job::Agent(_))
539                            .then(|| self.out_dir(&key))
540                            .flatten();
541                        let folder = &folder;
542                        scope.spawn(move || {
543                            let finished =
544                                job.run(&key, agent, folder, deadline, cost_left, keep.as_deref());
545                            let _ = send.send((key, finished));
546                        });
547                    }
548                }
549                if self.working.is_empty() || matches!(ended, Err(Halt::Stop(_))) {
550                    if let (Err(Halt::Pause), Some((at, step)), false) =
551                        (&ended, self.soonest.clone(), self.detach)
552                    {
553                        if self.working.is_empty() {
554                            self.tell(&format!("Waiting until {} for the step {step}.", words(at)));
555                            self.told();
556                            self.clock
557                                .wait_until(self.end.map_or(at, |end| end.min(at)));
558                            continue;
559                        }
560                    }
561                    self.working.clear();
562                    return (ended, steps);
563                }
564                let mut finished = Vec::new();
565                let first = match self.soonest.as_ref().map(|(at, _)| *at) {
566                    Some(at) => {
567                        let left = Duration::try_from(at.duration_since(self.clock.now()))
568                            .unwrap_or(Duration::ZERO);
569                        receive
570                            .recv_timeout(left.max(Duration::from_millis(10)))
571                            .ok()
572                    }
573                    None => receive.recv().ok(),
574                };
575                finished.extend(first);
576                finished.extend(receive.try_iter());
577                for (key, done) in finished {
578                    self.finish(key, done, &mut entries, &mut readers, &mut before, &folder);
579                }
580                self.hand_out(&entries);
581            }
582        })
583    }
584
585    /// Keeps the record of the run as it stands while it goes on, waiting for the person to say whether each work
586    /// that cannot be undone and is out was done, should the run stop before it ends.
587    fn keep_meanwhile(&mut self, steps: &[StepRecord], entries: &[Entry]) {
588        let Some(draft) = self.draft.clone() else {
589            return;
590        };
591        let waiting = Outcome::Waiting(self.out.clone());
592        let record = self.as_it_stands(draft, waiting, steps.to_vec(), entries.to_vec());
593        if let Err(error) = record.keep(&self.folder) {
594            self.person.tell(&format!(
595                "The record of this run could not be kept: {error}"
596            ));
597        }
598    }
599
600    /// Hands the keeper each entry it was not handed yet, or that changed since. Whether there was any.
601    fn hand_out(&mut self, entries: &[Entry]) -> bool {
602        let mut any = false;
603        for entry in entries {
604            if self.handed.get(&entry.key) == Some(entry) {
605                continue;
606            }
607            any = true;
608            if let Some(keeper) = self.keeper.as_deref_mut() {
609                keeper.kept(entry);
610            }
611            self.handed.insert(entry.key.clone(), entry.clone());
612        }
613        any
614    }
615
616    /// The record of the run as it stands now, from its record as it started.
617    fn as_it_stands(
618        &self,
619        mut record: Record,
620        outcome: Outcome,
621        steps: Vec<StepRecord>,
622        journal: Vec<Entry>,
623    ) -> Record {
624        record.ended = self.clock.now();
625        record.outcome = outcome;
626        record.cost = self.cost;
627        record.cost_unmeasured = self.unmeasured;
628        record.steps = steps;
629        record.decisions.clone_from(&self.decisions);
630        record.journal = journal;
631        record
632    }
633
634    /// Keeps what an agent or a command gave when it ended: its answer for the journal, the error of an agent, or
635    /// why the run stops. An agent that may only read and changed the folder stops the run, whatever it gave.
636    fn finish(
637        &mut self,
638        key: String,
639        done: Finished,
640        entries: &mut Vec<Entry>,
641        readers: &mut HashMap<String, String>,
642        before: &mut Option<u64>,
643        folder: &Path,
644    ) {
645        self.working.remove(&key);
646        match done {
647            Finished::Agent(Err(error)) => entries.push(Entry {
648                key: key.clone(),
649                at: self.clock.now(),
650                by: None,
651                value: serde_json::to_value(AgentError { error }).unwrap_or_default(),
652            }),
653            done => match done.value() {
654                Ok(value) => entries.push(Entry {
655                    key: key.clone(),
656                    at: self.clock.now(),
657                    by: None,
658                    value,
659                }),
660                Err(why) => {
661                    self.failures.insert(key.clone(), why);
662                }
663            },
664        }
665        if let Some(guard) = readers.remove(&key) {
666            if readers.is_empty() && before.take() != Some(folder::digest(folder)) {
667                self.failures.insert(key, guard);
668            }
669        }
670    }
671
672    /// Now: the computer's clock, or while the run goes over what it was given before, the time of the last of it.
673    fn now(&self) -> Timestamp {
674        if self.journal.live {
675            self.clock.now()
676        } else {
677            self.journal.time
678        }
679    }
680
681    /// Tells the person, when the run does something new: what leads only to what the run was given before, the
682    /// person heard then.
683    fn tell(&mut self, text: &str) {
684        self.held.push(text.to_owned());
685    }
686
687    /// Tells the person what is held.
688    fn told(&mut self) {
689        for text in std::mem::take(&mut self.held) {
690            self.person.tell(&text);
691        }
692    }
693
694    /// The run does something new: from here on it asks and reads the clock for itself, and what it would have
695    /// told since the last thing it was given before is told now.
696    fn go_live(&mut self) {
697        self.journal.live = true;
698        self.told();
699    }
700
701    /// What the run was given before under `key`, and who gave it. What led to it was told then.
702    fn recall<T: DeserializeOwned>(&mut self, key: &str) -> Option<(T, Option<String>)> {
703        let found = self.journal.recall(key)?;
704        self.held.clear();
705        Some(found)
706    }
707
708    fn keep<T: Serialize>(&mut self, key: String, value: &T) {
709        let now = self.clock.now();
710        self.journal.keep(key, value, now);
711    }
712
713    /// The time kept under `key`, or now, kept.
714    fn moment(&mut self, key: String) -> Timestamp {
715        if let Some((at, _)) = self.recall(&key) {
716            return at;
717        }
718        self.go_live();
719        let now = self.clock.now();
720        self.keep(key, &now);
721        now
722    }
723
724    /// The person's reply under `key`, and who gave it: given before, or asked now. When no one answers now, or
725    /// the run asks no one, the step waits for it.
726    fn reply(
727        &mut self,
728        key: String,
729        step: &str,
730        wait: Wait,
731    ) -> Result<(Reply, Option<String>), Halt> {
732        if let Some(found) = self.recall::<Reply>(&key) {
733            return Ok(found);
734        }
735        if !self.detach {
736            self.go_live();
737            let reply = match &wait {
738                Wait::Answer(ask) => self.person.answer(ask).map(Reply::Text),
739                Wait::Approval(ask) => self.person.approve(ask).map(|verdict| match verdict {
740                    Verdict::Yes => Reply::Yes,
741                    Verdict::No { points, back } => Reply::No { points, back },
742                }),
743                Wait::Decision(question) => self.person.decide(question).map(|yes| {
744                    if yes {
745                        Reply::Yes
746                    } else {
747                        Reply::No {
748                            points: String::new(),
749                            back: Vec::new(),
750                        }
751                    }
752                }),
753                Wait::Choice { question, options } => {
754                    self.person.choose(question, options).map(Reply::Option)
755                }
756                Wait::Time(_) => None,
757            };
758            if let Some(reply) = reply {
759                self.keep(key, &reply);
760                return Ok((reply, None));
761            }
762        }
763        self.waiting.push(Waiting {
764            step: step.to_owned(),
765            key,
766            wait,
767        });
768        Err(Halt::Pause)
769    }
770
771    /// A text the person gives under `key`.
772    fn text(
773        &mut self,
774        key: String,
775        step: &str,
776        ask: Ask,
777    ) -> Result<(String, Option<String>), Halt> {
778        let (reply, by) = self.reply(key, step, Wait::Answer(ask))?;
779        Ok((
780            match reply {
781                Reply::Text(text) => text,
782                _ => String::new(),
783            },
784            by,
785        ))
786    }
787
788    /// Runs the steps of a plan, each when the steps it waits for are done and its time has come. The answer of
789    /// the last step when they are all done.
790    fn steps(
791        &mut self,
792        plan: &Plan,
793        asked: &str,
794        records: &mut Vec<StepRecord>,
795        base: &str,
796    ) -> Result<String, Halt> {
797        let started = self.moment(format!("{base}@start"));
798        let graph = Graph::of(plan);
799        let mut progress = vec![Progress::default(); plan.steps.len()];
800        records.extend(plan.steps.iter().map(|step| StepRecord::new(&step.id)));
801        let ended = self.order(plan, asked, &graph, &mut progress, records, base, started);
802        for (record, step) in records.iter_mut().zip(&progress) {
803            record.ended = step.state.ended();
804        }
805        ended?;
806        Ok(progress
807            .last()
808            .map(|last| last.answer.clone())
809            .unwrap_or_default())
810    }
811
812    #[allow(clippy::too_many_arguments)]
813    fn order(
814        &mut self,
815        plan: &Plan,
816        asked: &str,
817        graph: &Graph<'_>,
818        progress: &mut [Progress],
819        records: &mut [StepRecord],
820        base: &str,
821        started: Timestamp,
822    ) -> Result<(), Halt> {
823        loop {
824            self.within_limits()?;
825            match self.look(plan, graph, progress, records, started) {
826                Look::Start(number) => {
827                    self.start(plan, asked, graph, progress, records, base, number)?;
828                }
829                Look::Again => {}
830                Look::Wait(at, number) => self.wait(&plan.steps[number], base, at)?,
831                Look::Done => return Ok(()),
832                Look::Stuck if progress.iter().any(|step| step.state == State::Parked) => {
833                    return Err(Halt::Pause);
834                }
835                Look::Stuck => return Err("no step can start".to_owned().into()),
836            }
837        }
838    }
839
840    /// Starts a step and keeps how it ended. A step that waits for an answer is parked, and the run goes on with
841    /// the steps that do not wait for it.
842    #[allow(clippy::too_many_arguments)]
843    fn start(
844        &mut self,
845        plan: &Plan,
846        asked: &str,
847        graph: &Graph<'_>,
848        progress: &mut [Progress],
849        records: &mut [StepRecord],
850        base: &str,
851        number: usize,
852    ) -> Result<(), Halt> {
853        let id = &plan.steps[number].id;
854        let skipped: HashSet<String> = progress
855            .iter()
856            .zip(&plan.steps)
857            .filter(|(step, _)| step.state == State::Skipped)
858            .map(|(_, step)| step.id.clone())
859            .collect();
860        let mut values = Values::from([("asked".to_owned(), asked.to_owned())]);
861        for &wait in &graph.all_waits[number] {
862            values.insert(plan.steps[wait].id.clone(), progress[wait].answer.clone());
863        }
864        let round = progress[number].rounds;
865        progress[number].rounds += 1;
866        let started = self.moment(format!("{base}{id}@start{round}"));
867        let place = Place {
868            base,
869            round,
870            started,
871        };
872        let ended = match self.step(
873            plan,
874            number,
875            &values,
876            &skipped,
877            &mut progress[number],
878            &mut records[number],
879            &place,
880        ) {
881            Ok(ended) => ended,
882            Err(Halt::Pause) => {
883                progress[number].state = State::Parked;
884                return Ok(());
885            }
886            Err(halt) => return Err(halt),
887        };
888        let now = self.moment(format!("{base}{id}@done{round}"));
889        if let Some(told) = settle(graph, progress, &mut records[number], number, ended, now) {
890            self.tell(&told);
891        }
892        Ok(())
893    }
894
895    /// Waits for a step's time: the step waits, and the run waits for the soonest time once nothing else can go
896    /// on. A run going over what it was given before does not wait for a time that has passed.
897    fn wait(&mut self, step: &Step, base: &str, at: Timestamp) -> Result<(), Halt> {
898        if !self.journal.live && at <= self.clock.now() {
899            self.journal.time = self.journal.time.max(at);
900            return Ok(());
901        }
902        if self
903            .soonest
904            .as_ref()
905            .is_none_or(|(soonest, _)| at < *soonest)
906        {
907            self.soonest = Some((at, step.id.clone()));
908        }
909        self.waiting.push(Waiting {
910            step: step.id.clone(),
911            key: format!("{base}{}@time", step.id),
912            wait: Wait::Time(at),
913        });
914        Err(Halt::Pause)
915    }
916
917    /// Finds the first step that may start, skipping the steps whose path was not taken on the way.
918    fn look(
919        &mut self,
920        plan: &Plan,
921        graph: &Graph,
922        progress: &mut [Progress],
923        records: &mut [StepRecord],
924        started: Timestamp,
925    ) -> Look {
926        let now = self.now();
927        let mut soonest: Option<(Timestamp, usize)> = None;
928        let mut changed = false;
929        for (number, step) in plan.steps.iter().enumerate() {
930            if progress[number].state != State::Open
931                || graph.waits[number]
932                    .iter()
933                    .any(|&wait| !progress[wait].state.ended())
934            {
935                continue;
936            }
937            if let Some((on, answer)) = step.when.as_ref().and_then(|when| when.iter().next()) {
938                let chose = &progress[graph.index[on.as_str()]];
939                if chose.state == State::Skipped || chose.answer != *answer {
940                    progress[number] = Progress {
941                        state: State::Skipped,
942                        done: Some(now),
943                        ..Progress::default()
944                    };
945                    records[number].skipped = true;
946                    self.tell(&format!(
947                        "Step {} · {}: skipped, since {on} did not answer {answer}.",
948                        number + 1,
949                        step.id
950                    ));
951                    changed = true;
952                    continue;
953                }
954            }
955            if let Some(at) = not_before(step, &graph.waits[number], progress, started) {
956                if at > now {
957                    if soonest.is_none_or(|(soonest, _)| at < soonest) {
958                        soonest = Some((at, number));
959                    }
960                    continue;
961                }
962            }
963            return Look::Start(number);
964        }
965        if changed {
966            Look::Again
967        } else if progress.iter().all(|step| step.state.ended()) {
968            Look::Done
969        } else if let Some((at, number)) = soonest {
970            Look::Wait(at, number)
971        } else {
972            Look::Stuck
973        }
974    }
975
976    fn within_limits(&self) -> Result<(), Halt> {
977        // The run's time is over when it is over now, even while the run goes over what it was given before.
978        if self.end.is_some_and(|end| self.clock.now() >= end) {
979            return Err(Self::time_over().into());
980        }
981        match self.cost_limit {
982            Some(limit) if self.cost >= limit => Err(format!(
983                "the run has cost {}, which reaches its limit of {limit}",
984                self.cost
985            )
986            .into()),
987            _ => Ok(()),
988        }
989    }
990
991    fn time_over() -> String {
992        "the run reached its deadline, or the runner's own time limit".to_owned()
993    }
994
995    /// When the run's time is over, on the computer's own clock, for commands and agents to stop by.
996    fn instant(&self) -> Option<Instant> {
997        let left = self.end?.duration_since(self.clock.now());
998        Some(Instant::now() + Duration::try_from(left).unwrap_or(Duration::ZERO))
999    }
1000
1001    /// Does one step, for each of its items when it has them.
1002    #[allow(clippy::too_many_arguments)]
1003    fn step(
1004        &mut self,
1005        plan: &Plan,
1006        number: usize,
1007        values: &Values,
1008        skipped: &HashSet<String>,
1009        progress: &mut Progress,
1010        record: &mut StepRecord,
1011        place: &Place<'_>,
1012    ) -> Result<Ended, Halt> {
1013        let step = &plan.steps[number];
1014        let header = |values: &Values| {
1015            let item = values
1016                .get("item")
1017                .map(|item| format!(" ({item})"))
1018                .unwrap_or_default();
1019            format!(
1020                "Step {} · {}{item}: {}",
1021                number + 1,
1022                step.id,
1023                fill(&step.what, values)
1024            )
1025        };
1026        let scope = format!("{}{}/", place.base, step.id);
1027        let Some(list) = &step.for_each else {
1028            let header = header(values);
1029            // A person's step is its own question, and so is work that cannot be undone, so it is not told twice.
1030            if step.by != By::Person && !step.irreversible() {
1031                self.tell(&header);
1032            }
1033            let again = progress.again.take();
1034            return self.work_until_proven(
1035                plan,
1036                step,
1037                &header,
1038                values,
1039                skipped,
1040                again,
1041                &mut progress.refused,
1042                place.started,
1043                &scope,
1044                &mut record.attempts,
1045            );
1046        };
1047
1048        let items = items(values.get(list).map_or("", String::as_str));
1049        if items.len() > MANY_ITEMS {
1050            let asked = format!(
1051                "The step {} is done for each of {} items. Go on?",
1052                step.id,
1053                items.len()
1054            );
1055            let key = format!("{}{}@many{}", place.base, step.id, place.round);
1056            if !self.decide(key, &step.id, asked)? {
1057                return Err(format!(
1058                    "the person did not go on with the {} items of the step {}",
1059                    items.len(),
1060                    step.id
1061                )
1062                .into());
1063            }
1064        }
1065        // Work sent back to this step goes to every item, with the points against it.
1066        let again = progress.again.take().map(|(_, points)| points);
1067        let mut answers = Vec::new();
1068        let mut paused = false;
1069        for (at, item) in items.into_iter().enumerate() {
1070            let mut values = values.clone();
1071            values.insert("item".to_owned(), item.clone());
1072            let header = header(&values);
1073            if step.by != By::Person && !step.irreversible() {
1074                self.tell(&header);
1075            }
1076            // An item done again keeps its earlier attempts.
1077            if record.items.get(at).is_none_or(|kept| kept.item != item) {
1078                record.items.truncate(at);
1079                record.items.push(ItemRecord {
1080                    item,
1081                    answer: None,
1082                    attempts: Vec::new(),
1083                });
1084            }
1085            let done = &mut record.items[at];
1086            let sent_back = again
1087                .clone()
1088                .map(|points| (done.answer.take().unwrap_or_default(), points));
1089            let mut refused = 0;
1090            let ended = self.work_until_proven(
1091                plan,
1092                step,
1093                &header,
1094                &values,
1095                skipped,
1096                sent_back,
1097                &mut refused,
1098                place.started,
1099                &format!("{scope}{}#{at}/", place.round),
1100                &mut done.attempts,
1101            );
1102            match ended {
1103                Ok(Ended::Passed(answer)) => {
1104                    done.answer = Some(answer.clone());
1105                    answers.push(serde_json::Value::String(answer));
1106                }
1107                Ok(Ended::LeftOut | Ended::Back { .. }) => return Ok(Ended::LeftOut),
1108                // Items one by one wait for the one before; the others go on while one waits.
1109                Err(Halt::Pause) if step.one_by_one() => return Err(Halt::Pause),
1110                Err(Halt::Pause) => paused = true,
1111                Err(halt) => return Err(halt),
1112            }
1113        }
1114        if paused {
1115            return Err(Halt::Pause);
1116        }
1117        Ok(Ended::Passed(serde_json::Value::Array(answers).to_string()))
1118    }
1119
1120    /// Does a step's work, or an item's, until its proofs pass, the person goes on without it, or a proof sends
1121    /// the work back to earlier steps.
1122    #[allow(clippy::too_many_arguments)]
1123    fn work_until_proven(
1124        &mut self,
1125        plan: &Plan,
1126        step: &Step,
1127        header: &str,
1128        values: &Values,
1129        skipped: &HashSet<String>,
1130        mut last: Option<(String, String)>,
1131        refused: &mut u32,
1132        started: Timestamp,
1133        scope: &str,
1134        attempts: &mut Vec<Attempt>,
1135    ) -> Result<Ended, Halt> {
1136        let mut fixing: Option<String> = None;
1137        let mut deadline = step
1138            .deadline
1139            .as_deref()
1140            .and_then(Moment::read)
1141            .map(|deadline| deadline.from(started));
1142        loop {
1143            self.within_limits()?;
1144            let at = format!("{scope}{}/", attempts.len());
1145            if let Some(end) = deadline.filter(|end| self.now() >= *end) {
1146                match self.late(step, end, &at)? {
1147                    Some(later) => deadline = Some(later),
1148                    None => return Ok(Ended::LeftOut),
1149                }
1150            }
1151            let mut attempt = Attempt::by(by_name(step.by));
1152            let out = self.undone(plan, step, header, values, skipped, &at)?;
1153            if let Out::Back(to, points) = out {
1154                attempt.back.clone_from(&to);
1155                attempts.push(attempt);
1156                return Ok(Ended::Back { to, points });
1157            }
1158            let worker = self.worker(step, values, &at)?;
1159            attempt.conversation = self.begin_work(step, &at, &out, attempts);
1160            let work = match out {
1161                Out::Done(answer) => Ok(answer),
1162                Out::NotDone => Err(Halt::Failed(NOT_DONE.to_owned())),
1163                Out::Fresh | Out::Back(..) => self.work(
1164                    plan,
1165                    step,
1166                    header,
1167                    values,
1168                    worker.as_deref(),
1169                    last.as_ref(),
1170                    fixing.as_deref(),
1171                    &at,
1172                    &mut attempt,
1173                ),
1174            };
1175            if work.is_ok() && step.by != By::Plan {
1176                attempt.changed = self.changed(&at);
1177            }
1178            let judged = work.and_then(|answer| {
1179                let answer = match &step.choices {
1180                    Some(choices) => chosen(&answer, choices),
1181                    None => answer,
1182                };
1183                let points = self.judge(
1184                    plan,
1185                    step,
1186                    values,
1187                    skipped,
1188                    &answer,
1189                    worker.as_deref(),
1190                    &at,
1191                    &mut attempt,
1192                )?;
1193                Ok((answer, points))
1194            });
1195            let (answer, points) = match judged {
1196                Ok(judged) => judged,
1197                // The agent's error is the point against this work alone, and the rest of the run goes on.
1198                Err(Halt::Failed(points)) => {
1199                    (String::new(), Some(attempt.failed.insert(points).clone()))
1200                }
1201                Err(reason) => {
1202                    attempts.push(attempt);
1203                    return Err(reason);
1204                }
1205            };
1206            self.before.remove(&at);
1207            let back = attempt.back.clone();
1208            attempts.push(attempt);
1209            let Some(points) = points else {
1210                return Ok(Ended::Passed(answer));
1211            };
1212
1213            self.tell(&format!("Refused: {points}"));
1214            *refused += 1;
1215            if *refused >= self.repeats {
1216                let asked = format!(
1217                    "The step {} was refused {} times. The last points against it: {points}\nGo on?",
1218                    step.id, *refused
1219                );
1220                if !self.decide(format!("{at}repeat"), &step.id, asked)? {
1221                    return Err(format!(
1222                        "the person did not go on after the step {} was refused {} times",
1223                        step.id, *refused
1224                    )
1225                    .into());
1226                }
1227                *refused = 0;
1228            }
1229            if !back.is_empty() {
1230                return Ok(Ended::Back { to: back, points });
1231            }
1232            if step.by == By::Algorithm && step.on_fail == Some(OnFail::Agent) {
1233                fixing = Some(points.clone());
1234            }
1235            last = Some((answer, points));
1236        }
1237    }
1238
1239    /// The points against an attempt's answer, or `None` when it stands: the command of an algorithm, the
1240    /// choices, then each proof in order until one refuses. A refusal that names earlier steps keeps them in the
1241    /// attempt.
1242    #[allow(clippy::too_many_arguments)]
1243    fn judge(
1244        &mut self,
1245        plan: &Plan,
1246        step: &Step,
1247        values: &Values,
1248        skipped: &HashSet<String>,
1249        answer: &str,
1250        worker: Option<&str>,
1251        at: &str,
1252        attempt: &mut Attempt,
1253    ) -> Result<Option<String>, Halt> {
1254        if let Some(points) = attempt
1255            .proofs
1256            .iter()
1257            .find(|proof| !proof.passed)
1258            .and_then(|proof| proof.points.clone())
1259        {
1260            return Ok(Some(points));
1261        }
1262        if let Some(choices) = step
1263            .choices
1264            .as_ref()
1265            .filter(|choices| !choices.iter().any(|choice| choice == answer))
1266        {
1267            let listed = choices.join(", ");
1268            let against = format!("The answer must be exactly one of: {listed}. It was: {answer}");
1269            attempt.proofs.push(ProofRecord {
1270                by: "algorithm".to_owned(),
1271                asked: format!("The answer is one of: {listed}"),
1272                passed: false,
1273                points: Some(against.clone()),
1274                skipped: false,
1275                reason: None,
1276            });
1277            return Ok(Some(against));
1278        }
1279        let mut own = values.clone();
1280        own.insert(step.id.clone(), answer.to_owned());
1281        let mut passed: Vec<String> = attempt
1282            .proofs
1283            .iter()
1284            .map(|proof| format!("The command `{}` ended with 0.", proof.asked))
1285            .collect();
1286        for (count, proof) in step.proofs().iter().enumerate() {
1287            let other_path = proof.when.as_ref().is_some_and(|when| {
1288                when.iter()
1289                    .any(|(id, answer)| own.get(id).is_none_or(|given| given != answer))
1290            });
1291            if other_path {
1292                attempt.proofs.push(ProofRecord {
1293                    by: prover_name(proof.by).to_owned(),
1294                    asked: proof_asked(proof, &own),
1295                    passed: false,
1296                    points: None,
1297                    skipped: true,
1298                    reason: proof
1299                        .when
1300                        .as_ref()
1301                        .map(|when| path_words(when, &own, skipped)),
1302                });
1303                continue;
1304            }
1305            let offered: Vec<String> = proof
1306                .back_to
1307                .iter()
1308                .flatten()
1309                .filter(|id| !skipped.contains(*id))
1310                .cloned()
1311                .collect();
1312            let key = format!(
1313                "{at}proof{count}:{}",
1314                stamp(&serde_json::to_string(proof).unwrap_or_default())
1315            );
1316            let asked = Asked {
1317                proof,
1318                values: &own,
1319                answer,
1320                worker,
1321                offered: &offered,
1322                key,
1323                at,
1324                passed: &passed,
1325            };
1326            let (proved, back) = self.prove(plan, step, &asked)?;
1327            let against = (!proved.passed).then(|| proved.points.clone().unwrap_or_default());
1328            if proved.passed {
1329                passed.push(passed_words(proof, &proved.asked));
1330            }
1331            attempt.proofs.push(proved);
1332            if against.is_some() {
1333                attempt.back = back;
1334                return Ok(against);
1335            }
1336        }
1337        Ok(None)
1338    }
1339
1340    /// For work that cannot be undone: the person's yes first, then whether it was done when the run stopped while
1341    /// it was out.
1342    fn undone(
1343        &mut self,
1344        plan: &Plan,
1345        step: &Step,
1346        header: &str,
1347        values: &Values,
1348        skipped: &HashSet<String>,
1349        at: &str,
1350    ) -> Result<Out, Halt> {
1351        if !step.irreversible() {
1352            return Ok(Out::Fresh);
1353        }
1354        if let Some((to, points)) = self.approve_undone(plan, step, header, values, skipped, at)? {
1355            return Ok(Out::Back(to, points));
1356        }
1357        self.out_before(step, header, values, at)
1358    }
1359
1360    /// Asks the person who asked whether to start work that cannot be undone, telling them what it does with its
1361    /// references filled. A no stops the run, unless it sends the work back to earlier steps: then those steps, with
1362    /// the points against the work.
1363    fn approve_undone(
1364        &mut self,
1365        plan: &Plan,
1366        step: &Step,
1367        header: &str,
1368        values: &Values,
1369        skipped: &HashSet<String>,
1370        at: &str,
1371    ) -> Result<Option<(Vec<String>, String)>, Halt> {
1372        let mut question = header.to_owned();
1373        match step.by {
1374            By::Algorithm => {
1375                let line = fill(step.run.as_deref().unwrap_or_default(), values);
1376                let _ = write!(question, "\nIt runs `{line}`.");
1377            }
1378            By::Plan => {
1379                let _ = write!(
1380                    question,
1381                    "\nIt runs the plan `{}`.",
1382                    step.plan.as_deref().unwrap_or_default()
1383                );
1384            }
1385            By::Agent | By::Person => {}
1386        }
1387        question.push_str("\nIt cannot be undone. Start it?");
1388        let offered = if step.for_each.is_some() {
1389            Vec::new()
1390        } else {
1391            let graph = Graph::of(plan);
1392            let waits = &graph.all_waits[graph.index[step.id.as_str()]];
1393            plan.steps
1394                .iter()
1395                .enumerate()
1396                .filter(|(number, earlier)| {
1397                    waits.contains(number)
1398                        && !earlier.irreversible()
1399                        && !skipped.contains(&earlier.id)
1400                })
1401                .map(|(_, earlier)| earlier.id.clone())
1402                .collect()
1403        };
1404        let ask = Ask {
1405            question: question.clone(),
1406            people: Vec::new(),
1407            choices: Vec::new(),
1408            back_to: offered.clone(),
1409        };
1410        let (reply, by) = self.reply(format!("{at}start"), &step.id, Wait::Approval(ask))?;
1411        let refused = match reply {
1412            Reply::No { points, back } => Some((points, back)),
1413            _ => None,
1414        };
1415        self.decisions.push(Decision {
1416            step: step.id.clone(),
1417            asked: question,
1418            answer: if refused.is_some() { "no" } else { "yes" }.to_owned(),
1419            by,
1420        });
1421        let Some((points, back)) = refused else {
1422            return Ok(None);
1423        };
1424        let back: Vec<String> = back.into_iter().filter(|id| offered.contains(id)).collect();
1425        if back.is_empty() {
1426            let why = if points.trim().is_empty() {
1427                String::new()
1428            } else {
1429                format!(": {}", points.trim())
1430            };
1431            return Err(format!(
1432                "the person did not start the step {}, which cannot be undone{why}",
1433                step.id
1434            )
1435            .into());
1436        }
1437        let points = if points.trim().is_empty() {
1438            "The person said no.".to_owned()
1439        } else {
1440            points
1441        };
1442        self.tell(&format!("Refused: {points}"));
1443        Ok(Some((back, points)))
1444    }
1445
1446    /// Where work that cannot be undone stands as an attempt begins. Work by an agent or a command that began
1447    /// before the run stopped, with no end kept, is not done again on its own: a command still running is waited
1448    /// for, and one that ended is taken as it ended; otherwise the person says whether it was done, and what it
1449    /// answered. Work that is out is listed, so that the record kept meanwhile asks the same.
1450    fn out_before(
1451        &mut self,
1452        step: &Step,
1453        header: &str,
1454        values: &Values,
1455        at: &str,
1456    ) -> Result<Out, Halt> {
1457        let end = match step.by {
1458            By::Agent => "work",
1459            By::Algorithm => "run",
1460            By::Person | By::Plan => return Ok(Out::Fresh),
1461        };
1462        let (begun, end) = (format!("{at}begun"), format!("{at}{end}"));
1463        if self.journal.knows(&end) {
1464            return Ok(Out::Fresh);
1465        }
1466        let key = format!("{at}done");
1467        let question = format!(
1468            "{header}\nThis work cannot be undone. It began before the run stopped, and how it ended was not kept: \
1469             was it done? Yes goes on to its proofs; no does it again."
1470        );
1471        if self.journal.knows(&begun) && !self.asked.contains(&end) {
1472            if let Some(dir) = self.out_dir(at).filter(|_| step.by == By::Algorithm) {
1473                if let Some(pid) = command::still_running(&dir) {
1474                    self.tell(&format!(
1475                        "{header}\nIts work, which cannot be undone, is still running from before the run stopped \
1476                         (process {pid}): the run waits for it to end."
1477                    ));
1478                    self.go_live();
1479                    while command::still_running(&dir).is_some() {
1480                        thread::sleep(Duration::from_millis(200));
1481                    }
1482                }
1483                if let Some(ended) = command::kept(&dir) {
1484                    self.go_live();
1485                    self.keep(end, &ended);
1486                    return Ok(Out::Fresh);
1487                }
1488            }
1489            // Its commands that prove it, when they need not its answer, may tell that it was done.
1490            match self.proven_done(step, values, at)? {
1491                Ok(()) => {}
1492                Err(found) => {
1493                    let question = match found {
1494                        Some(points) => format!(
1495                            "{question}\nIts proof by a command found: {}",
1496                            points.trim()
1497                        ),
1498                        None => question,
1499                    };
1500                    if !self.decide(key, &step.id, question)? {
1501                        return Ok(Out::NotDone);
1502                    }
1503                }
1504            }
1505            let ask = Ask {
1506                question: format!(
1507                    "{header}\nWhat did it answer? Leave it empty when it does not matter."
1508                ),
1509                ..Ask::default()
1510            };
1511            let (answer, _) = self.text(format!("{at}said"), &step.id, ask)?;
1512            return Ok(Out::Done(answer.trim().to_owned()));
1513        }
1514        if !self.journal.knows(&begun) {
1515            self.go_live();
1516            self.keep(begun, &true);
1517        }
1518        self.out.push(Waiting {
1519            step: step.id.clone(),
1520            key,
1521            wait: Wait::Decision(question),
1522        });
1523        Ok(Out::Fresh)
1524    }
1525
1526    /// Whether the proofs of a step by commands and needs, those that do not name its own answer and are for every
1527    /// path, all pass now: then its work, whose end was lost, was done. Otherwise what the first that refused found,
1528    /// or nothing when it has none.
1529    fn proven_done(
1530        &mut self,
1531        step: &Step,
1532        values: &Values,
1533        at: &str,
1534    ) -> Result<Result<(), Option<String>>, Halt> {
1535        let mut marked = values.clone();
1536        marked.insert(step.id.clone(), "\0".to_owned());
1537        let proofs: Vec<&Proof> = step
1538            .proofs()
1539            .iter()
1540            .filter(|proof| proof.by == Prover::Algorithm && proof.when.is_none())
1541            .filter(|proof| {
1542                !fill(&serde_json::to_string(proof).unwrap_or_default(), &marked).contains('\0')
1543            })
1544            .collect();
1545        if proofs.is_empty() {
1546            return Ok(Err(None));
1547        }
1548        for (count, proof) in proofs.into_iter().enumerate() {
1549            let key = format!("{at}check{count}");
1550            let points = match &proof.run {
1551                Some(run) => {
1552                    let line = fill(run, values);
1553                    let ended = self.command(key, &line)?;
1554                    (!ended.passed).then(|| ended.points(&line))
1555                }
1556                None => self.needs(key, proof, values).1,
1557            };
1558            if points.is_some() {
1559                return Ok(Err(points));
1560            }
1561        }
1562        self.tell("Its proofs by commands pass now, so it was done.");
1563        Ok(Ok(()))
1564    }
1565
1566    /// Where the command of work that cannot be undone at `at` writes its process, its output and how it ended, so
1567    /// that a run that stopped meanwhile finds them: only for a run whose record is kept.
1568    fn out_dir(&self, at: &str) -> Option<PathBuf> {
1569        let draft = self.draft.as_ref()?;
1570        Some(
1571            runs(&self.folder)
1572                .join(format!("{}.out", draft.id))
1573                .join(stamp(at)),
1574        )
1575    }
1576
1577    /// The agent that does an attempt of a step by an agent.
1578    fn worker(&mut self, step: &Step, values: &Values, at: &str) -> Result<Option<String>, Halt> {
1579        if step.by != By::Agent {
1580            return Ok(None);
1581        }
1582        let key = format!("{at}agent");
1583        self.agent_named(step, step.agent.as_deref(), values, None, key)
1584    }
1585
1586    /// Keeps the folder as it is before an attempt's work begins, to tell its proofs what changed. The conversation
1587    /// the step's last refused work went on in, which its agent is told and may go on in.
1588    fn begin_work(
1589        &mut self,
1590        step: &Step,
1591        at: &str,
1592        out: &Out,
1593        attempts: &[Attempt],
1594    ) -> Option<String> {
1595        if step.by != By::Plan && !self.before.contains_key(at) && !self.work_begun(at) {
1596            self.before
1597                .insert(at.to_owned(), folder::snapshot(&self.folder));
1598        }
1599        let fresh = step.by == By::Agent && matches!(out, Out::Fresh);
1600        fresh.then(|| last_conversation(attempts)).flatten()
1601    }
1602
1603    /// The files the work of an attempt changed, kept when its work ended, or recalled. Nothing when the run did
1604    /// not see its work begin.
1605    fn changed(&mut self, at: &str) -> Vec<String> {
1606        let key = format!("{at}changed");
1607        if let Some((paths, _)) = self.recall(&key) {
1608            return paths;
1609        }
1610        let Some(before) = self.before.get(at) else {
1611            return Vec::new();
1612        };
1613        let paths = folder::changed(before, &folder::snapshot(&self.folder));
1614        self.go_live();
1615        self.keep(key, &paths);
1616        paths
1617    }
1618
1619    /// Whether the work of an attempt began: an agent, a command or a person was asked for it.
1620    fn work_begun(&self, at: &str) -> bool {
1621        ["work", "fix", "run", "answer"]
1622            .iter()
1623            .any(|end| self.journal.knows(&format!("{at}{end}")))
1624    }
1625
1626    /// Asks the person a yes or no question about a step, and keeps what they decided.
1627    fn decide(&mut self, key: String, step: &str, asked: String) -> Result<bool, Halt> {
1628        let (reply, by) = self.reply(key, step, Wait::Decision(asked.clone()))?;
1629        let yes = reply == Reply::Yes;
1630        self.decisions.push(Decision {
1631            step: step.to_owned(),
1632            asked,
1633            answer: if yes { "yes" } else { "no" }.to_owned(),
1634            by,
1635        });
1636        Ok(yes)
1637    }
1638
1639    /// Asks the person what to do with a step past its deadline: a later deadline, `None` to go on without it, or
1640    /// a stop.
1641    fn late(&mut self, step: &Step, end: Timestamp, at: &str) -> Result<Option<Timestamp>, Halt> {
1642        let asked = format!(
1643            "The step {} reached its deadline, {}, before it passed. What now?",
1644            step.id,
1645            words(end)
1646        );
1647        let options: Vec<String> = LATE.map(str::to_owned).to_vec();
1648        let mut count = 0;
1649        loop {
1650            let wait = Wait::Choice {
1651                question: asked.clone(),
1652                options: options.clone(),
1653            };
1654            let (reply, by) = self.reply(format!("{at}late{count}"), &step.id, wait)?;
1655            let chosen = match reply {
1656                Reply::Option(chosen) => Some(chosen),
1657                _ => None,
1658            };
1659            self.decisions.push(Decision {
1660                step: step.id.clone(),
1661                asked: asked.clone(),
1662                answer: chosen
1663                    .and_then(|chosen| LATE.get(chosen))
1664                    .map_or("none", |chosen| *chosen)
1665                    .to_owned(),
1666                by,
1667            });
1668            match chosen {
1669                Some(0) => {
1670                    let until = Ask {
1671                        question: "Until when? A date such as 2027-03-10T18:00-03:00, or a wait such as P2D."
1672                            .to_owned(),
1673                        ..Ask::default()
1674                    };
1675                    let (text, _) = self.text(format!("{at}late{count}/until"), &step.id, until)?;
1676                    let now = self.now();
1677                    let later = Moment::read(&text)
1678                        .map(|later| later.from(now))
1679                        .filter(|later| *later > now);
1680                    if let Some(later) = later {
1681                        return Ok(Some(later));
1682                    }
1683                    self.tell("That is not a later time.");
1684                }
1685                Some(1) => return Ok(None),
1686                _ => {
1687                    return Err(format!(
1688                        "the step {} reached its deadline and the person stopped the run",
1689                        step.id
1690                    )
1691                    .into());
1692                }
1693            }
1694            count += 1;
1695        }
1696    }
1697
1698    /// The agent a step or proof names, filled. When a reference gives nothing, or the agent would judge its own
1699    /// work, the person is asked whom to give it to.
1700    fn agent_named(
1701        &mut self,
1702        step: &Step,
1703        named: Option<&str>,
1704        values: &Values,
1705        worker: Option<&str>,
1706        key: String,
1707    ) -> Result<Option<String>, Halt> {
1708        let Some(named) = named else {
1709            return Ok(None);
1710        };
1711        let filled = fill(named, values).trim().to_owned();
1712        let question = if filled.is_empty() {
1713            format!(
1714                "The step {} names its agent by “{named}”, which gives nothing. Which agent should it go to? \
1715                 Leave it empty to stop.",
1716                step.id
1717            )
1718        } else if worker.is_some_and(|worker| worker == filled) {
1719            format!(
1720                "The agent {filled} would judge its own work in the step {}. Which agent should judge it? \
1721                 Leave it empty to stop.",
1722                step.id
1723            )
1724        } else {
1725            return Ok(Some(filled));
1726        };
1727        let ask = Ask {
1728            question: question.clone(),
1729            ..Ask::default()
1730        };
1731        let (answer, by) = self.text(key, &step.id, ask)?;
1732        let answer = answer.trim().to_owned();
1733        self.decisions.push(Decision {
1734            step: step.id.clone(),
1735            asked: question,
1736            answer: if answer.is_empty() {
1737                "none".to_owned()
1738            } else {
1739                answer.clone()
1740            },
1741            by,
1742        });
1743        if answer.is_empty() || worker.is_some_and(|worker| worker == answer) {
1744            return Err(format!("the person named no agent for the step {}", step.id).into());
1745        }
1746        Ok(Some(answer))
1747    }
1748
1749    /// The people a step or proof names, filled. When a reference gives nothing, the person is asked.
1750    fn people(
1751        &mut self,
1752        step: &Step,
1753        ids: Option<&vpf::Ids>,
1754        values: &Values,
1755        key: &str,
1756    ) -> Result<Vec<String>, Halt> {
1757        let mut people = Vec::new();
1758        for (count, id) in ids
1759            .map(vpf::Ids::list)
1760            .unwrap_or_default()
1761            .iter()
1762            .enumerate()
1763        {
1764            let filled = fill(id, values).trim().to_owned();
1765            if !filled.is_empty() {
1766                people.push(filled);
1767                continue;
1768            }
1769            let question = format!(
1770                "The step {} names a person by “{id}”, which gives nothing. Whom should it go to? Leave it empty \
1771                 to stop.",
1772                step.id
1773            );
1774            let ask = Ask {
1775                question: question.clone(),
1776                ..Ask::default()
1777            };
1778            let (answer, by) = self.text(format!("{key}person{count}"), &step.id, ask)?;
1779            let answer = answer.trim().to_owned();
1780            self.decisions.push(Decision {
1781                step: step.id.clone(),
1782                asked: question,
1783                answer: if answer.is_empty() {
1784                    "none".to_owned()
1785                } else {
1786                    answer.clone()
1787                },
1788                by,
1789            });
1790            if answer.is_empty() {
1791                return Err(format!("the person named no one for the step {}", step.id).into());
1792            }
1793            people.push(answer);
1794        }
1795        Ok(people)
1796    }
1797
1798    /// Does the work of one attempt. For an algorithm, the command is recorded as the attempt's first proof.
1799    #[allow(clippy::too_many_arguments)]
1800    fn work(
1801        &mut self,
1802        plan: &Plan,
1803        step: &Step,
1804        header: &str,
1805        values: &Values,
1806        worker: Option<&str>,
1807        last: Option<&(String, String)>,
1808        fixing: Option<&str>,
1809        at: &str,
1810        attempt: &mut Attempt,
1811    ) -> Result<String, Halt> {
1812        match step.by {
1813            By::Agent => {
1814                let prompt = work_prompt(plan, step, values, last);
1815                let tools: Vec<&'static str> = match &step.tools {
1816                    Some(tools) => tools.iter().copied().map(tool_name).collect(),
1817                    None => ALL_TOOLS.to_vec(),
1818                };
1819                let may_write = tools.contains(&"write");
1820                let request = Request {
1821                    role: Role::Work,
1822                    step: step.id.clone(),
1823                    conversation: attempt.conversation.take(),
1824                    prompt,
1825                    agent: worker.map(str::to_owned),
1826                    model: step.model.clone(),
1827                    tools,
1828                    guard: (!may_write).then(|| {
1829                        format!(
1830                            "the agent of the step {} changed the folder, but its step does not give it write",
1831                            step.id
1832                        )
1833                    }),
1834                };
1835                let answer = self.ask(format!("{at}work"), request)?;
1836                attempt.answer = Some(answer.text.clone());
1837                attempt.conversation = answer.conversation;
1838                Ok(answer.text)
1839            }
1840            By::Person => {
1841                let people = self.people(step, step.person.as_ref(), values, at)?;
1842                let mut question = header.to_owned();
1843                if let Some((answer, points)) = last {
1844                    let _ = write!(
1845                        question,
1846                        "\nYour last answer, “{answer}”, was refused: {points}"
1847                    );
1848                }
1849                let ask = Ask {
1850                    question,
1851                    people,
1852                    choices: step.choices.clone().unwrap_or_default(),
1853                    back_to: Vec::new(),
1854                };
1855                let (answer, _) = self.text(format!("{at}answer"), &step.id, ask)?;
1856                attempt.answer = Some(answer.clone());
1857                Ok(answer)
1858            }
1859            By::Plan => {
1860                let answer = self.other_plan(step, values, at, attempt)?;
1861                attempt.answer = Some(answer.clone());
1862                Ok(answer)
1863            }
1864            By::Algorithm => {
1865                let line = fill(step.run.as_deref().unwrap_or_default(), values);
1866                if let Some(points) = fixing {
1867                    "agent".clone_into(&mut attempt.by);
1868                    let request = Request {
1869                        role: Role::Fix,
1870                        step: step.id.clone(),
1871                        conversation: None,
1872                        prompt: fix_prompt(plan, step, &line, points),
1873                        agent: None,
1874                        model: None,
1875                        tools: ALL_TOOLS.to_vec(),
1876                        guard: None,
1877                    };
1878                    let fixed = self.ask(format!("{at}fix"), request)?;
1879                    attempt.answer = Some(fixed.text);
1880                }
1881                let keep = if step.irreversible() {
1882                    self.out_dir(at)
1883                } else {
1884                    None
1885                };
1886                let ended: command::Ended = self.answered(format!("{at}run"), || Job::Command {
1887                    line: line.clone(),
1888                    keep,
1889                })?;
1890                attempt.proofs.push(ProofRecord {
1891                    by: "algorithm".to_owned(),
1892                    points: (!ended.passed).then(|| ended.points(&line)),
1893                    asked: line,
1894                    passed: ended.passed,
1895                    skipped: false,
1896                    reason: None,
1897                });
1898                if fixing.is_none() {
1899                    attempt.answer = Some(ended.out.trim().to_owned());
1900                }
1901                Ok(ended.out.trim().to_owned())
1902            }
1903        }
1904    }
1905
1906    /// Runs a command line in the folder, or recalls how it ended when the run was given that before.
1907    fn command(&mut self, key: String, line: &str) -> Result<command::Ended, Halt> {
1908        self.answered(key, || Job::Command {
1909            line: line.to_owned(),
1910            keep: None,
1911        })
1912    }
1913
1914    /// What an agent or command answered under `key`, when it has. Otherwise it is started, or keeps working, and
1915    /// the step waits for it.
1916    fn answered<T: DeserializeOwned>(
1917        &mut self,
1918        key: String,
1919        job: impl FnOnce() -> Job,
1920    ) -> Result<T, Halt> {
1921        if let Some(why) = self.failures.get(&key) {
1922            return Err(Halt::Stop(why.clone()));
1923        }
1924        if let Some((AgentError { error }, _)) = self.recall(&key) {
1925            return Err(Halt::Failed(format!("{AGENT_ERROR}{error}")));
1926        }
1927        if let Some((answer, _)) = self.recall(&key) {
1928            return Ok(answer);
1929        }
1930        if self.asked.contains(&key) {
1931            // What led to it was told when it was first asked.
1932            self.held.clear();
1933            self.journal.live = true;
1934        } else {
1935            self.go_live();
1936            self.asked.insert(key.clone());
1937        }
1938        if !self.working.contains(&key) {
1939            self.jobs.push((key, job()));
1940        }
1941        Err(Halt::Pause)
1942    }
1943
1944    /// Asks the agent, or recalls its answer when the run was given it before. With a guard, the agent may not
1945    /// change the folder, and the run stops with the guard if it does.
1946    fn ask(&mut self, key: String, request: Request) -> Result<AgentAnswer, Halt> {
1947        let answer: AgentAnswer = self.answered(key, || Job::Agent(request))?;
1948        if let Some(cost) = answer.cost {
1949            self.cost += cost;
1950        } else {
1951            self.unmeasured = true;
1952            if self.cost_limit.is_some() && !self.told_unmeasured {
1953                self.told_unmeasured = true;
1954                self.tell(
1955                    "The agent did not say what it cost, so this run's cost is not measured against its limit.",
1956                );
1957            }
1958        }
1959        Ok(answer)
1960    }
1961
1962    /// Asks one proof of the work: what it found, and the earlier steps its refusal sends the work back to.
1963    fn prove(
1964        &mut self,
1965        plan: &Plan,
1966        step: &Step,
1967        asked: &Asked<'_>,
1968    ) -> Result<(ProofRecord, Vec<String>), Halt> {
1969        let Asked {
1970            proof,
1971            values,
1972            answer,
1973            offered,
1974            ref key,
1975            ..
1976        } = *asked;
1977        let by = prover_name(proof.by);
1978        let result = |asked: String, points: Option<String>| ProofRecord {
1979            by: by.to_owned(),
1980            asked,
1981            passed: points.is_none(),
1982            points,
1983            skipped: false,
1984            reason: None,
1985        };
1986        match proof.by {
1987            Prover::Algorithm => {
1988                if let Some(run) = &proof.run {
1989                    let line = fill(run, values);
1990                    let ended = self.command(key.clone(), &line)?;
1991                    if ended.passed {
1992                        return Ok((result(line, None), Vec::new()));
1993                    }
1994                    let (back, points) = named_first(&ended.points(&line), offered);
1995                    Ok((result(line, Some(points)), back))
1996                } else {
1997                    let (asked, points) = self.needs(key.clone(), proof, values);
1998                    Ok((result(asked, points), Vec::new()))
1999                }
2000            }
2001            Prover::Agent => {
2002                let (check, points, back) = self.prove_by_agent(plan, step, asked)?;
2003                Ok((result(check, points), back))
2004            }
2005            Prover::Person => {
2006                let people =
2007                    self.people(step, proof.person.as_ref(), values, &format!("{key}/"))?;
2008                let question = match &proof.ask {
2009                    Some(ask) if !ask.trim().is_empty() && answer.trim().is_empty() => {
2010                        fill(ask, values)
2011                    }
2012                    Some(ask) if !ask.trim().is_empty() => format!(
2013                        "{}\nThe answer of the step {}:\n{}\n",
2014                        fill(ask, values),
2015                        step.id,
2016                        answer.trim()
2017                    ),
2018                    _ => format!(
2019                        "Do you approve the step {}, “{}”? Its answer:\n{answer}\n",
2020                        step.id,
2021                        fill(&step.what, values)
2022                    ),
2023                };
2024                let ask = Ask {
2025                    question: question.clone(),
2026                    people,
2027                    choices: Vec::new(),
2028                    back_to: offered.to_vec(),
2029                };
2030                match self.reply(key.clone(), &step.id, Wait::Approval(ask))?.0 {
2031                    Reply::No { points, back } => {
2032                        let points = if points.trim().is_empty() {
2033                            "The person said no.".to_owned()
2034                        } else {
2035                            points
2036                        };
2037                        let back = back.into_iter().filter(|id| offered.contains(id)).collect();
2038                        Ok((result(question, Some(points)), back))
2039                    }
2040                    _ => Ok((result(question, None), Vec::new())),
2041                }
2042            }
2043        }
2044    }
2045
2046    /// Asks another agent to prove the work: what it was asked to find true, its points against the work, and the
2047    /// earlier steps they send it back to.
2048    fn prove_by_agent(
2049        &mut self,
2050        plan: &Plan,
2051        step: &Step,
2052        asked: &Asked<'_>,
2053    ) -> Result<(String, Option<String>, Vec<String>), Halt> {
2054        let Asked {
2055            proof,
2056            values,
2057            answer,
2058            worker,
2059            offered,
2060            ref key,
2061            at,
2062            passed,
2063        } = *asked;
2064        let named = format!("{key}/agent");
2065        let judge = self.agent_named(step, proof.agent.as_deref(), values, worker, named)?;
2066        let check = fill(proof.check.as_deref().unwrap_or_default(), values);
2067        let changed = if self.journal.knows(key) {
2068            None
2069        } else {
2070            self.before.get(at).map(|before| {
2071                let now = folder::snapshot(&self.folder);
2072                let paths = folder::changed(before, &now);
2073                let lines = folder::changes(before, &now, &paths);
2074                (paths, lines)
2075            })
2076        };
2077        let witness = Witness {
2078            answer,
2079            passed,
2080            changed: changed.as_ref().map(|(paths, _)| paths.as_slice()),
2081            changes: changed.as_ref().map_or("", |(_, lines)| lines.as_str()),
2082        };
2083        let request = Request {
2084            role: Role::Judge,
2085            step: step.id.clone(),
2086            conversation: None,
2087            prompt: judge_prompt(plan, step, values, &witness, &check, offered),
2088            agent: judge,
2089            model: proof.model.clone(),
2090            tools: proof.tools.as_deref().map_or_else(
2091                || vec!["read"],
2092                |tools| tools.iter().copied().map(tool_name).collect(),
2093            ),
2094            guard: Some(format!(
2095                "the agent that proved the step {} changed the folder, but it may only read",
2096                step.id
2097            )),
2098        };
2099        let said = self.ask(key.clone(), request)?.text;
2100        let points = verdict(&said);
2101        let back = points
2102            .as_deref()
2103            .map(|points| named_in_points(points, offered))
2104            .unwrap_or_default();
2105        Ok((check, points, back))
2106    }
2107
2108    /// Checks the needs of a proof in the folder, or recalls what was missing when the run was given that before:
2109    /// the needs in words, and what is missing.
2110    fn needs(&mut self, key: String, proof: &Proof, values: &Values) -> (String, Option<String>) {
2111        let needs: Vec<vpf::Need> = proof
2112            .needs()
2113            .iter()
2114            .map(|need| fill_need(need, values))
2115            .collect();
2116        let asked = needs.iter().map(describe).collect::<Vec<_>>().join("; ");
2117        let missing: Vec<String> = if let Some((missing, _)) = self.recall(&key) {
2118            missing
2119        } else {
2120            self.go_live();
2121            let missing: Vec<String> = needs
2122                .iter()
2123                .filter_map(|need| meets(&self.folder, need).err())
2124                .collect();
2125            self.keep(key, &missing);
2126            missing
2127        };
2128        (asked, (!missing.is_empty()).then(|| missing.join("\n")))
2129    }
2130
2131    /// Runs the plan a step names, as that step.
2132    fn other_plan(
2133        &mut self,
2134        step: &Step,
2135        values: &Values,
2136        at: &str,
2137        attempt: &mut Attempt,
2138    ) -> Result<String, Halt> {
2139        let name = step.plan.clone().unwrap_or_default();
2140        if self.stack.contains(&name) {
2141            return Err(format!("the plan {name} runs itself, in a loop").into());
2142        }
2143        let key = format!("{at}plan");
2144        let text = if let Some((text, _)) = self.recall::<String>(&key) {
2145            text
2146        } else {
2147            self.go_live();
2148            let file = self.plans.join(format!("{name}.vpf.json"));
2149            let text = fs::read_to_string(&file)
2150                .map_err(|_| format!("cannot find the plan {name}, in {}", file.display()))?;
2151            self.keep(key, &text);
2152            text
2153        };
2154        let report = vpf::check(&text);
2155        let Some(other) = report.plan.filter(|_| report.problems.is_empty()) else {
2156            let problems: Vec<String> = report.problems.iter().map(ToString::to_string).collect();
2157            return Err(format!("the plan {name} has problems: {}", problems.join("; ")).into());
2158        };
2159        self.stack.push(name);
2160        let asked = match &step.asked {
2161            None => fill(&step.what, values),
2162            Some(vpf::Asked::Text(text)) => fill(text, values),
2163            Some(vpf::Asked::Fields(fields)) => serde_json::Value::Object(
2164                fields
2165                    .iter()
2166                    .map(|(name, value)| (name.clone(), fill_json(value, values)))
2167                    .collect(),
2168            )
2169            .to_string(),
2170        };
2171        attempt.steps.clear();
2172        let ended = self.steps(&other, &asked, &mut attempt.steps, at);
2173        self.stack.pop();
2174        ended
2175    }
2176}
2177
2178/// Where a step runs: under which keys of the journal, its round, and when it started.
2179struct Place<'k> {
2180    base: &'k str,
2181    round: u32,
2182    started: Timestamp,
2183}
2184
2185/// The conversation the last refused work of a step went on in, which its agent is told and may go on in.
2186fn last_conversation(attempts: &[Attempt]) -> Option<String> {
2187    attempts
2188        .iter()
2189        .rev()
2190        .find_map(|earlier| earlier.conversation.clone())
2191}
2192
2193/// What an agent is asked, before the runner adds the folder and the time left.
2194struct Request {
2195    role: Role,
2196    /// The step it is asked for.
2197    step: String,
2198    /// The conversation of the step's refused work.
2199    conversation: Option<String>,
2200    prompt: String,
2201    agent: Option<String>,
2202    model: Option<String>,
2203    tools: Vec<&'static str>,
2204    /// When the agent may not change the folder: why the run stops if it does.
2205    guard: Option<String>,
2206}
2207
2208/// An agent or a command a step asks, to work while the run goes on.
2209enum Job {
2210    Agent(Request),
2211    /// A command line, and where it keeps its process, its output and how it ended, for work that cannot be
2212    /// undone.
2213    Command {
2214        line: String,
2215        keep: Option<PathBuf>,
2216    },
2217}
2218
2219/// The error an agent ended with, as the journal keeps it: the work it was given is refused with it.
2220#[derive(Serialize, serde::Deserialize)]
2221#[serde(deny_unknown_fields)]
2222struct AgentError {
2223    error: String,
2224}
2225
2226/// What an agent or a command gave when it ended.
2227enum Finished {
2228    Agent(Result<AgentAnswer, String>),
2229    Command(Result<command::Ended, TimeOver>),
2230}
2231
2232impl Job {
2233    /// Why the run stops when this agent changes the folder, for an agent that may only read.
2234    fn guard(&self) -> Option<&str> {
2235        match self {
2236            Self::Agent(request) => request.guard.as_deref(),
2237            Self::Command { .. } => None,
2238        }
2239    }
2240
2241    fn run(
2242        self,
2243        key: &str,
2244        agent: &dyn Agent,
2245        folder: &Path,
2246        deadline: Option<Instant>,
2247        cost_left: Option<f64>,
2248        keep: Option<&Path>,
2249    ) -> Finished {
2250        match self {
2251            Self::Agent(request) => Finished::Agent(agent.ask(&AgentRequest {
2252                role: request.role,
2253                step: &request.step,
2254                key,
2255                conversation: request.conversation.as_deref(),
2256                cost_left,
2257                keep,
2258                prompt: request.prompt,
2259                agent: request.agent.as_deref(),
2260                model: request.model.as_deref(),
2261                tools: request.tools,
2262                folder,
2263                deadline,
2264            })),
2265            Self::Command { line, keep: None } => {
2266                Finished::Command(command::run(&line, folder, &[], "", deadline))
2267            }
2268            Self::Command {
2269                line,
2270                keep: Some(keep),
2271            } => Finished::Command(command::run_kept(&line, folder, &[], "", &keep, deadline)),
2272        }
2273    }
2274}
2275
2276impl Finished {
2277    /// What to keep in the journal, or why the run stops.
2278    fn value(self) -> Result<serde_json::Value, String> {
2279        let kept = match self {
2280            Self::Agent(answer) => serde_json::to_value(answer?),
2281            Self::Command(ended) => {
2282                serde_json::to_value(ended.map_err(|TimeOver| Runner::time_over())?)
2283            }
2284        };
2285        kept.map_err(|error| error.to_string())
2286    }
2287}
2288
2289/// One proof to ask of an answer.
2290struct Asked<'a> {
2291    proof: &'a Proof,
2292    values: &'a Values,
2293    answer: &'a str,
2294    worker: Option<&'a str>,
2295    offered: &'a [String],
2296    key: String,
2297    /// The key of the attempt the proof is asked of.
2298    at: &'a str,
2299    /// The proofs of this attempt that passed before this one, in words.
2300    passed: &'a [String],
2301}
2302
2303/// What an agent that proves work is shown of it.
2304struct Witness<'a> {
2305    answer: &'a str,
2306    /// The proofs that passed before, in words.
2307    passed: &'a [String],
2308    /// The files the work changed, when the runner knows.
2309    changed: Option<&'a [String]>,
2310    /// The lines the work removed and added in the text files it changed, as a unified diff.
2311    changes: &'a str,
2312}
2313
2314/// Why a proof for one path was not asked: the answer it is for, and what was given.
2315fn path_words(
2316    when: &std::collections::BTreeMap<String, String>,
2317    values: &Values,
2318    skipped: &HashSet<String>,
2319) -> String {
2320    when.iter()
2321        .map(|(id, answer)| {
2322            let given = if skipped.contains(id) {
2323                "it was skipped".to_owned()
2324            } else {
2325                format!(
2326                    "it answered “{}”",
2327                    values.get(id).map_or("", String::as_str)
2328                )
2329            };
2330            format!("Only when {id} answers “{answer}”; {given}.")
2331        })
2332        .collect::<Vec<_>>()
2333        .join(" ")
2334}
2335
2336/// What a proof asks, with references filled, for the record of a proof that was not asked.
2337fn proof_asked(proof: &Proof, values: &Values) -> String {
2338    let text = match proof.by {
2339        Prover::Algorithm => proof.run.as_deref(),
2340        Prover::Agent => proof.check.as_deref(),
2341        Prover::Person => proof.ask.as_deref(),
2342    };
2343    match text {
2344        Some(text) => fill(text, values),
2345        None if proof.by == Prover::Algorithm => "Its needs".to_owned(),
2346        None => "Whether the work is good".to_owned(),
2347    }
2348}
2349
2350fn passed_words(proof: &Proof, asked: &str) -> String {
2351    match proof.by {
2352        Prover::Algorithm if proof.run.is_some() => format!("The command `{asked}` ended with 0."),
2353        Prover::Algorithm => format!("These are there: {asked}."),
2354        Prover::Agent => format!("Another agent found this true: “{asked}”"),
2355        Prover::Person => format!(
2356            "A person approved: {}",
2357            asked.lines().next().unwrap_or_default()
2358        ),
2359    }
2360}
2361
2362/// What the run knows of the order of a plan's steps.
2363struct Graph<'p> {
2364    index: HashMap<&'p str, usize>,
2365    /// The steps each step waits for itself.
2366    waits: Vec<Vec<usize>>,
2367    /// The steps each step waits for, and the steps those wait for.
2368    all_waits: Vec<HashSet<usize>>,
2369}
2370
2371impl<'p> Graph<'p> {
2372    fn of(plan: &'p Plan) -> Self {
2373        let index: HashMap<&str, usize> = plan
2374            .steps
2375            .iter()
2376            .enumerate()
2377            .map(|(number, step)| (step.id.as_str(), number))
2378            .collect();
2379        let waits: Vec<Vec<usize>> = (0..plan.steps.len())
2380            .map(|number| direct_waits(plan, number, &index))
2381            .collect();
2382        let all_waits = transitive(&waits);
2383        Self {
2384            index,
2385            waits,
2386            all_waits,
2387        }
2388    }
2389}
2390
2391/// What the run may do next.
2392enum Look {
2393    /// Start this step.
2394    Start(usize),
2395    /// Look again: steps were skipped.
2396    Again,
2397    /// Wait until this time, when this step may start.
2398    Wait(Timestamp, usize),
2399    /// Every step is done.
2400    Done,
2401    /// No step can start and none waits for a time.
2402    Stuck,
2403}
2404
2405/// Keeps how a step ended. When its work went back to earlier steps, opens them again with the points, and every
2406/// step between them and it, and says so.
2407fn settle(
2408    graph: &Graph<'_>,
2409    progress: &mut [Progress],
2410    record: &mut StepRecord,
2411    number: usize,
2412    ended: Ended,
2413    now: Timestamp,
2414) -> Option<String> {
2415    match ended {
2416        Ended::Passed(answer) => {
2417            record.answer = Some(answer.clone());
2418            let step = &mut progress[number];
2419            step.state = State::Passed;
2420            step.answer = answer;
2421            step.done = Some(now);
2422            step.again = None;
2423            None
2424        }
2425        Ended::LeftOut => {
2426            record.skipped = true;
2427            let step = &mut progress[number];
2428            step.state = State::Skipped;
2429            step.answer = String::new();
2430            step.done = Some(now);
2431            None
2432        }
2433        Ended::Back { to, points } => {
2434            let chosen: Vec<usize> = to.iter().map(|id| graph.index[id.as_str()]).collect();
2435            for (other, again) in progress.iter_mut().enumerate() {
2436                let between = graph.all_waits[number].contains(&other)
2437                    && chosen
2438                        .iter()
2439                        .any(|&one| graph.all_waits[other].contains(&one));
2440                if chosen.contains(&other) {
2441                    again.state = State::Open;
2442                    again.again = Some((again.answer.clone(), points.clone()));
2443                } else if between {
2444                    again.state = State::Open;
2445                    again.again = None;
2446                }
2447            }
2448            Some(format!("The work goes back to {}.", to.join(", ")))
2449        }
2450    }
2451}
2452
2453/// When a step may start, when it has `not_before`: a date, or a wait from when the steps it waits for are done,
2454/// or from the start of the run.
2455fn not_before(
2456    step: &Step,
2457    waits: &[usize],
2458    progress: &[Progress],
2459    started: Timestamp,
2460) -> Option<Timestamp> {
2461    let moment = Moment::read(step.not_before.as_deref()?)?;
2462    let from = waits
2463        .iter()
2464        .filter_map(|&wait| progress[wait].done)
2465        .max()
2466        .unwrap_or(started);
2467    Some(moment.from(from))
2468}
2469
2470/// The steps a step waits for itself: its `after`, or the step written before it.
2471fn direct_waits(plan: &Plan, number: usize, index: &HashMap<&str, usize>) -> Vec<usize> {
2472    match &plan.steps[number].after {
2473        Some(after) => after
2474            .iter()
2475            .filter_map(|id| index.get(id.as_str()).copied())
2476            .collect(),
2477        None => number.checked_sub(1).into_iter().collect(),
2478    }
2479}
2480
2481/// For each step, every step it waits for, and every step those wait for.
2482fn transitive(waits: &[Vec<usize>]) -> Vec<HashSet<usize>> {
2483    let mut all: Vec<HashSet<usize>> = Vec::with_capacity(waits.len());
2484    // A step waits only for steps written before it, so theirs are known first.
2485    for direct in waits {
2486        let mut set = HashSet::new();
2487        for &wait in direct {
2488            set.insert(wait);
2489            set.extend(all[wait].iter().copied());
2490        }
2491        all.push(set);
2492    }
2493    all
2494}
2495
2496/// The items of an answer: the items of a JSON array, or each line that is not blank.
2497fn items(answer: &str) -> Vec<String> {
2498    if let Ok(serde_json::Value::Array(list)) = serde_json::from_str(answer.trim()) {
2499        return list.iter().map(text).collect();
2500    }
2501    answer
2502        .lines()
2503        .map(str::trim)
2504        .filter(|line| !line.is_empty())
2505        .map(str::to_owned)
2506        .collect()
2507}
2508
2509/// A command's refusal: the offered steps it names, one per line, at the start of what it wrote, and the rest.
2510fn named_first(said: &str, offered: &[String]) -> (Vec<String>, String) {
2511    let mut back = Vec::new();
2512    let mut lines = said.lines().peekable();
2513    while let Some(line) = lines.peek() {
2514        let id = line.trim();
2515        if offered.iter().any(|offered| offered == id) {
2516            if !back.iter().any(|named: &String| named == id) {
2517                back.push(id.to_owned());
2518            }
2519            lines.next();
2520        } else {
2521            break;
2522        }
2523    }
2524    let rest = lines.collect::<Vec<_>>().join("\n").trim().to_owned();
2525    if back.is_empty() || rest.is_empty() {
2526        (back, said.to_owned())
2527    } else {
2528        (back, rest)
2529    }
2530}
2531
2532/// A proving agent's refusal: the offered steps it names on a line `Back to: a, b`.
2533fn named_in_points(points: &str, offered: &[String]) -> Vec<String> {
2534    let mut back = Vec::new();
2535    for line in points.lines() {
2536        let line = line.trim();
2537        let Some(rest) = line
2538            .get(..8)
2539            .filter(|start| start.eq_ignore_ascii_case("back to:"))
2540            .map(|_| &line[8..])
2541        else {
2542            continue;
2543        };
2544        for id in rest.split([',', ' ']).map(str::trim) {
2545            if offered.iter().any(|offered| offered == id) && !back.iter().any(|named| named == id)
2546            {
2547                back.push(id.to_owned());
2548            }
2549        }
2550    }
2551    back
2552}
2553
2554/// The choice an answer gives: the answer itself, or the choice on its last line when the words before explain it.
2555fn chosen(answer: &str, choices: &[String]) -> String {
2556    let answer = answer.trim();
2557    let last = answer.lines().next_back().unwrap_or_default().trim();
2558    if !choices.iter().any(|choice| choice == answer) && choices.iter().any(|choice| choice == last)
2559    {
2560        return last.to_owned();
2561    }
2562    answer.to_owned()
2563}
2564
2565/// A JSON value with the references in every text inside it filled.
2566fn fill_json(value: &serde_json::Value, values: &Values) -> serde_json::Value {
2567    use serde_json::Value;
2568    match value {
2569        Value::String(text) => Value::String(fill(text, values)),
2570        Value::Array(list) => {
2571            Value::Array(list.iter().map(|value| fill_json(value, values)).collect())
2572        }
2573        Value::Object(fields) => Value::Object(
2574            fields
2575                .iter()
2576                .map(|(name, value)| (name.clone(), fill_json(value, values)))
2577                .collect(),
2578        ),
2579        other => other.clone(),
2580    }
2581}
2582
2583fn fill_need(need: &vpf::Need, values: &Values) -> vpf::Need {
2584    use vpf::Need;
2585    match need {
2586        Need::Files { path, at_least } => Need::Files {
2587            path: fill(path, values),
2588            at_least: *at_least,
2589        },
2590        Need::Folder { path } => Need::Folder {
2591            path: fill(path, values),
2592        },
2593        Need::Names { path, files } => Need::Names {
2594            path: fill(path, values),
2595            files: fill(files, values),
2596        },
2597        Need::Headings { path, headings } => Need::Headings {
2598            path: fill(path, values),
2599            headings: headings.clone(),
2600        },
2601        Need::Repository { path, branch } => Need::Repository {
2602            path: fill(path, values),
2603            branch: branch.clone(),
2604        },
2605    }
2606}
2607
2608/// `None` when a proving agent's answer passes the work, or the points against it.
2609fn verdict(said: &str) -> Option<String> {
2610    let mut lines = said.trim().lines();
2611    let first = lines.next().unwrap_or_default().trim().to_uppercase();
2612    let rest = lines.collect::<Vec<_>>().join("\n").trim().to_owned();
2613    if first.starts_with("PASS") {
2614        None
2615    } else if first.starts_with("FAIL") {
2616        Some(if rest.is_empty() {
2617            "The proving agent gave no points.".to_owned()
2618        } else {
2619            rest
2620        })
2621    } else {
2622        Some(format!(
2623            "The proving agent did not answer PASS or FAIL: {}",
2624            said.trim()
2625        ))
2626    }
2627}
2628
2629/// What will prove a step's work, one line per proof, in order.
2630fn proofs_in_words(step: &Step, values: &Values) -> String {
2631    let mut lines = String::new();
2632    let mut number = 0;
2633    let mut line = |text: String| {
2634        number += 1;
2635        let _ = writeln!(lines, "{number}. {text}");
2636    };
2637    if step.by == By::Algorithm {
2638        line(format!(
2639            "The command `{}` must pass.",
2640            fill(step.run.as_deref().unwrap_or_default(), values)
2641        ));
2642    }
2643    if let Some(choices) = &step.choices {
2644        line(format!(
2645            "The answer must be exactly one of: {}.",
2646            choices.join(", ")
2647        ));
2648    }
2649    for proof in step.proofs() {
2650        line(match proof.by {
2651            Prover::Algorithm => match &proof.run {
2652                Some(run) => format!("The command `{}` must pass.", fill(run, values)),
2653                None => format!(
2654                    "The folder must hold {}.",
2655                    proof
2656                        .needs()
2657                        .iter()
2658                        .map(|need| describe(&fill_need(need, values)))
2659                        .collect::<Vec<_>>()
2660                        .join("; ")
2661                ),
2662            },
2663            Prover::Agent => format!(
2664                "Another agent must find this true: “{}”",
2665                fill(proof.check.as_deref().unwrap_or_default(), values)
2666            ),
2667            Prover::Person => match &proof.ask {
2668                Some(ask) if !ask.trim().is_empty() => {
2669                    format!("A person must answer yes to: “{}”", fill(ask, values))
2670                }
2671                _ => "A person must approve your work.".to_owned(),
2672            },
2673        });
2674    }
2675    lines
2676}
2677
2678fn work_prompt(
2679    plan: &Plan,
2680    step: &Step,
2681    values: &Values,
2682    last: Option<&(String, String)>,
2683) -> String {
2684    let mut prompt = format!(
2685        "The wish: {}\n\nYour step, {}: {}\n\nWhat will prove your work, in this order:\n{}",
2686        plan.wish,
2687        step.id,
2688        fill(&step.what, values),
2689        proofs_in_words(step, values)
2690    );
2691    if let Some((answer, points)) = last {
2692        let _ = write!(
2693            prompt,
2694            "\nYour last answer was refused.\n\nYour last answer:\n{answer}\n\nThe points against it:\n{points}\n"
2695        );
2696    }
2697    match &step.choices {
2698        Some(choices) => {
2699            let _ = writeln!(
2700                prompt,
2701                "\nDo the work, then answer with exactly one of: {}. Write nothing else.",
2702                choices.join(", ")
2703            );
2704        }
2705        None => prompt.push_str("\nDo the work, then answer with what you did.\n"),
2706    }
2707    prompt
2708}
2709
2710fn fix_prompt(plan: &Plan, step: &Step, line: &str, points: &str) -> String {
2711    format!(
2712        "The wish: {}\n\nThe step {}: {}\n\nThe command `{line}` failed in the folder. What it wrote:\n{points}\n\n\
2713         Fix what stands in its way. Then the command runs again as the proof of your work, followed by the \
2714         step's own proofs:\n{}\nAnswer with what you changed.\n",
2715        plan.wish,
2716        step.id,
2717        step.what,
2718        proofs_in_words(step, &HashMap::new())
2719    )
2720}
2721
2722/// How many changed files a proving agent is shown by name.
2723const SHOWN_FILES: usize = 40;
2724
2725fn judge_prompt(
2726    plan: &Plan,
2727    step: &Step,
2728    values: &Values,
2729    witness: &Witness<'_>,
2730    check: &str,
2731    offered: &[String],
2732) -> String {
2733    let mut prompt = format!(
2734        "You prove another agent's work. Only read: do not change the folder.\n\nThe wish: {}\n\nThe step {}: {}\n\n\
2735         Its answer:\n{}\n\n",
2736        plan.wish,
2737        step.id,
2738        fill(&step.what, values),
2739        witness.answer
2740    );
2741    if !witness.passed.is_empty() {
2742        prompt.push_str("Already passed, before you:\n");
2743        for passed in witness.passed {
2744            let _ = writeln!(prompt, "- {passed}");
2745        }
2746        prompt.push('\n');
2747    }
2748    match witness.changed {
2749        Some([]) => prompt.push_str("The work changed no file in the folder.\n\n"),
2750        Some(changed) => {
2751            prompt.push_str(
2752                "Files the work changed, added or removed (steps working at the same time may have changed some):\n",
2753            );
2754            for path in changed.iter().take(SHOWN_FILES) {
2755                let _ = writeln!(prompt, "- {path}");
2756            }
2757            if changed.len() > SHOWN_FILES {
2758                let _ = writeln!(prompt, "- and {} more", changed.len() - SHOWN_FILES);
2759            }
2760            prompt.push('\n');
2761        }
2762        None => {}
2763    }
2764    if !witness.changes.is_empty() {
2765        prompt.push_str("The lines it removed (-) and added (+) in the text files:\n");
2766        prompt.push_str(witness.changes);
2767        prompt.push('\n');
2768    }
2769    let _ = write!(
2770        prompt,
2771        "Judge only whether this is true: “{check}”\n\
2772         What already passed is settled: do not judge it again.\n\n\
2773         Answer PASS or FAIL on the first line. After FAIL, give the points against the work.\n"
2774    );
2775    if !offered.is_empty() {
2776        let _ = writeln!(
2777            prompt,
2778            "When the fault is in the work of earlier steps, end with a line `Back to:` naming them, among: {}.",
2779            offered.join(", ")
2780        );
2781    }
2782    prompt
2783}
2784
2785#[cfg(test)]
2786mod tests {
2787    use super::{items, named_first, named_in_points, transitive};
2788
2789    fn ids(list: &[&str]) -> Vec<String> {
2790        list.iter().map(|&id| id.to_owned()).collect()
2791    }
2792
2793    #[test]
2794    fn a_step_waits_for_what_its_waits_wait_for() {
2795        let all = transitive(&[vec![], vec![0], vec![], vec![1, 2]]);
2796        assert!(all[3].contains(&0) && all[3].contains(&1) && all[3].contains(&2));
2797        assert!(all[2].is_empty());
2798    }
2799
2800    #[test]
2801    fn items_come_from_a_json_list_or_from_lines() {
2802        assert_eq!(items("a\n\n  b \n"), ["a", "b"]);
2803        assert_eq!(
2804            items(r#"["a", 2, {"x":1}, null]"#),
2805            ["a", "2", r#"{"x":1}"#, ""]
2806        );
2807        assert_eq!(items(""), Vec::<String>::new());
2808        assert_eq!(items("[]"), Vec::<String>::new());
2809    }
2810
2811    #[test]
2812    fn refusals_name_the_steps_to_send_back() {
2813        let offered = ids(&["intro", "numbers"]);
2814        assert_eq!(
2815            named_first("numbers\nintro\nnumbers\nThe totals are missing.", &offered),
2816            (
2817                ids(&["numbers", "intro"]),
2818                "The totals are missing.".to_owned()
2819            )
2820        );
2821        assert_eq!(
2822            named_first("ending\nNo.", &offered),
2823            (Vec::new(), "ending\nNo.".to_owned())
2824        );
2825        assert_eq!(
2826            named_in_points("They disagree.\nback to: numbers, ending", &offered),
2827            ids(&["numbers"])
2828        );
2829        assert_eq!(
2830            named_in_points("The numbers are wrong.", &offered),
2831            Vec::<String>::new()
2832        );
2833    }
2834}