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