vpf-runner 0.4.0

The reference runner of the Verifiable Plan Format (VPF): runs a plan step by step and proves each step.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
//! `vpf-run`: run a plan in the Verifiable Plan Format, step by step, proving each step.

use std::fs;
use std::io::{self, BufReader};
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use std::thread;
use std::time::Duration;

use clap::{Args, Parser, Subcommand};
use jiff::tz::TimeZone;
use jiff::{Timestamp, Zoned};
use vpf::{By, Plan, Prover, Start};
use vpf_runner::start::{Snapshot, Window, next_schedule};
use vpf_runner::{
    CommandAgent, Keeper, Moment, Outcome, Person, Record, Reply, Runner, Terminal, Wait,
    names_asked as names_asked_in,
};

/// Run a plan in the Verifiable Plan Format (VPF), step by step, proving each step.
#[derive(Parser)]
#[command(
    name = "vpf-run",
    version,
    about,
    args_conflicts_with_subcommands = true,
    subcommand_negates_reqs = true
)]
struct Cli {
    #[command(subcommand)]
    command: Option<Command>,
    /// The plan file.
    #[arg(required = true)]
    plan: Option<PathBuf>,
    #[command(flatten)]
    folder: FolderArg,
    #[command(flatten)]
    agent: AgentArg,
    /// What the run starts with, the text `{{asked}}` names. Asked of the person when the plan names it.
    #[arg(long)]
    asked: Option<String>,
    /// For a plan that starts on a schedule, every so many minutes or on files: stop after this many runs.
    #[arg(long)]
    runs: Option<u32>,
    /// Ask no one here and wait for no time: the run keeps what it waits for and ends, to go on later.
    #[arg(long)]
    detach: bool,
    /// How many agents and commands may work at the same time.
    #[arg(long, default_value_t = 8)]
    at_once: usize,
    /// How often to look for changed files, in milliseconds.
    #[arg(long, default_value_t = 2000, hide = true)]
    poll_ms: u64,
}

#[derive(Args)]
struct FolderArg {
    /// The folder the plan works in, where its runs are kept. The current folder when absent.
    #[arg(long)]
    folder: Option<PathBuf>,
}

#[derive(Args)]
struct AgentArg {
    /// The command that answers as an agent: it reads the prompt on its input and writes its answer.
    #[arg(long, env = "VPF_AGENT_COMMAND")]
    agent: Option<String>,
}

#[derive(Subcommand)]
enum Command {
    /// Show the runs that wait, what each waits for, and the steps whose time is near.
    Status {
        #[command(flatten)]
        folder: FolderArg,
    },
    /// Give a waiting run an answer it waits for.
    Answer {
        /// The run: its id, or the start of it.
        run: String,
        /// What the run waits for, as `vpf-run status` shows it.
        key: String,
        /// The answer: a text; yes, or no and what is wrong; or an option's number or words.
        #[arg(required = true, num_args = 1..)]
        reply: Vec<String>,
        /// Who answers, when the question is for named people.
        #[arg(long = "as")]
        by: Option<String>,
        /// After no: the earlier steps the work goes back to, joined by commas.
        #[arg(long)]
        back: Option<String>,
        #[command(flatten)]
        folder: FolderArg,
    },
    /// Go on with the runs that wait: the one named, or all of them.
    Go {
        /// The run: its id, or the start of it.
        run: Option<String>,
        /// Ask no one here and wait for no time.
        #[arg(long)]
        detach: bool,
        /// How many agents and commands may work at the same time.
        #[arg(long, default_value_t = 8)]
        at_once: usize,
        #[command(flatten)]
        folder: FolderArg,
        #[command(flatten)]
        agent: AgentArg,
    },
    /// Have a waiting run follow a new version of its plan, from where it stands.
    Change {
        /// The run: its id, or the start of it.
        run: String,
        /// The new version of the plan.
        plan: PathBuf,
        /// Who approves the new version: the person who asked for the run.
        #[arg(long)]
        approved_by: String,
        #[command(flatten)]
        folder: FolderArg,
    },
}

fn needs_agent(plan: &Plan) -> bool {
    plan.steps.iter().any(|step| {
        step.by == By::Agent
            || step.on_fail.is_some()
            || step.proofs().iter().any(|proof| proof.by == Prover::Agent)
    })
}

fn names_asked(plan: &Plan) -> bool {
    plan.steps.iter().any(|step| {
        let mut texts = vec![step.what.as_str()];
        texts.extend(step.run.as_deref());
        texts.extend(step.agent.as_deref());
        texts.extend(
            step.person
                .iter()
                .flat_map(vpf::Ids::list)
                .map(String::as_str),
        );
        for proof in step.proofs() {
            texts.extend(
                [&proof.run, &proof.check, &proof.ask, &proof.agent]
                    .into_iter()
                    .flatten()
                    .map(String::as_str),
            );
            texts.extend(
                proof
                    .person
                    .iter()
                    .flat_map(vpf::Ids::list)
                    .map(String::as_str),
            );
            texts.extend(proof.needs().iter().map(vpf::Need::path));
        }
        texts.into_iter().any(names_asked_in)
    })
}

/// The dates the plan writes that have already passed, in words.
fn passed_dates(plan: &Plan, now: Timestamp) -> Vec<String> {
    let mut dates: Vec<(String, String)> = Vec::new();
    if let Some(deadline) = plan.limits().deadline {
        dates.push(("the run's deadline".to_owned(), deadline));
    }
    for step in &plan.steps {
        if let Some(deadline) = &step.deadline {
            dates.push((format!("the deadline of {}", step.id), deadline.clone()));
        }
        if let Some(not_before) = &step.not_before {
            dates.push((format!("the start of {}", step.id), not_before.clone()));
        }
    }
    dates
        .into_iter()
        .filter(|(_, text)| matches!(Moment::read(text), Some(Moment::At(at)) if at < now))
        .map(|(what, text)| format!("{what}, {text}"))
        .collect()
}

fn name_of(file: &Path) -> String {
    let name = file
        .file_name()
        .and_then(|name| name.to_str())
        .unwrap_or("plan");
    name.strip_suffix(".vpf.json")
        .or_else(|| name.strip_suffix(".json"))
        .unwrap_or(name)
        .to_owned()
}

fn wait_until(person: &mut dyn Person, start: &Zoned) {
    person.tell(&format!(
        "Waiting until {}.",
        start.strftime("%A %Y-%m-%d %H:%M %Z")
    ));
    while let Ok(left) = Duration::try_from(start.duration_since(&Zoned::now())) {
        if left.is_zero() {
            break;
        }
        thread::sleep(left.min(Duration::from_secs(30)));
    }
}

/// Reads and checks the plan. Tells why it may not run.
fn load(file: &Path) -> Result<Plan, ExitCode> {
    let text = fs::read_to_string(file).map_err(|error| {
        eprintln!("vpf-run: cannot read {}: {error}", file.display());
        ExitCode::from(2)
    })?;
    let report = vpf::check(&text);
    if let (Some(plan), true) = (report.plan, report.problems.is_empty()) {
        return Ok(plan);
    }
    let count = report.problems.len();
    let noun = if count == 1 { "problem" } else { "problems" };
    println!("{}: {count} {noun}, it may not run", file.display());
    for problem in &report.problems {
        println!("  {problem}");
    }
    Err(ExitCode::from(1))
}

/// The exit code when no run may start: before the plan's `from` or after its `until`.
const CLOSED: u8 = 1;

/// Starts runs as the plan's start says, none before its `from` and none after its `until`. How the last run
/// ended, as an exit code.
fn serve(
    plan: &Plan,
    most: u32,
    poll: Duration,
    folder: &Path,
    person: &mut dyn Person,
    run_once: &mut dyn FnMut(&mut dyn Person) -> u8,
) -> u8 {
    let window = Window::of(plan);
    let closed = |person: &mut dyn Person, at: Timestamp| {
        let over = window.over(at);
        if over {
            person.tell(&format!(
                "No run starts after {}.",
                plan.runs_until().unwrap_or_default()
            ));
        }
        over
    };
    if closed(person, Timestamp::now()) {
        return CLOSED;
    }
    let start = plan.start();
    if let Some(from) = window.from.filter(|from| Timestamp::now() < *from) {
        if matches!(start, Start::Asked | Start::Request) {
            person.tell(&format!(
                "No run starts before {}.",
                plan.runs_from().unwrap_or_default()
            ));
            return CLOSED;
        }
        wait_until(person, &from.to_zoned(TimeZone::system()));
    }
    let mut done = CLOSED;
    match start {
        Start::Asked | Start::Request => done = run_once(person),
        Start::Schedule { days, dates, time } => {
            for _ in 0..most {
                let next = next_schedule(&days, &dates, &time, &Zoned::now());
                if closed(person, next.timestamp()) {
                    break;
                }
                wait_until(person, &next);
                done = run_once(person);
            }
        }
        Start::Every { minutes } => {
            for count in 0..most {
                if count > 0 {
                    person.tell(&format!("Waiting {minutes} minutes."));
                    thread::sleep(Duration::from_secs(u64::from(minutes) * 60));
                }
                if closed(person, Timestamp::now()) {
                    break;
                }
                done = run_once(person);
            }
        }
        Start::Files { paths } => {
            for _ in 0..most {
                person.tell(&format!("Waiting for a change to {}.", paths.join(", ")));
                let before = Snapshot::take(folder, &paths);
                while Snapshot::take(folder, &paths) == before {
                    thread::sleep(poll);
                }
                if closed(person, Timestamp::now()) {
                    break;
                }
                done = run_once(person);
            }
        }
    }
    done
}

/// The exit code of a run that waits.
const WAITING: u8 = 3;

/// Tells how a run ended, and what it waits for. Its exit code.
fn ended(person: &mut dyn Person, record: &Record) -> u8 {
    match &record.outcome {
        Outcome::Done => {
            person.tell("Done: every step passed its proofs.");
            0
        }
        Outcome::Stopped(reason) => {
            person.tell(&format!("Stopped: {reason}."));
            1
        }
        Outcome::Waiting(_) => {
            person.tell(&format!("The run {} waits, holding nothing:", record.id));
            person.tell(&waiting(record));
            WAITING
        }
    }
}

/// When a time is, in words: today, or its date.
fn when(at: Timestamp) -> String {
    let zone = TimeZone::system();
    let at = at.to_zoned(zone.clone());
    if at.date() == Zoned::now().with_time_zone(zone).date() {
        at.strftime("today at %H:%M").to_string()
    } else {
        at.strftime("on %Y-%m-%d at %H:%M (%:z)").to_string()
    }
}

/// What a waiting run waits for, one line each, and how to answer.
fn waiting(record: &Record) -> String {
    let Outcome::Waiting(list) = &record.outcome else {
        return String::new();
    };
    let mut lines = Vec::new();
    if list.is_empty() {
        lines.push("  It is running, or it stopped before it ended.".to_owned());
    }
    let mut answers = false;
    for waiting in list {
        let what = match &waiting.wait {
            Wait::Answer(ask) if ask.choices.is_empty() => ask.addressed(),
            Wait::Answer(ask) => {
                format!("{} (one of: {})", ask.addressed(), ask.choices.join(", "))
            }
            Wait::Approval(ask) if ask.back_to.is_empty() => {
                format!("{} (yes, or no and what is wrong)", ask.addressed())
            }
            Wait::Approval(ask) => format!(
                "{} (yes, or no and what is wrong; --back to send it back to some of: {})",
                ask.addressed(),
                ask.back_to.join(", ")
            ),
            Wait::Decision(question) => format!("{question} (yes or no)"),
            Wait::Choice { question, options } => {
                let numbered: Vec<String> = options
                    .iter()
                    .enumerate()
                    .map(|(number, option)| format!("{}. {option}", number + 1))
                    .collect();
                format!("{question} ({})", numbered.join("; "))
            }
            Wait::Time(at) => format!("The step {} may start {}.", waiting.step, when(*at)),
        };
        answers |= !matches!(waiting.wait, Wait::Time(_));
        lines.push(format!(
            "  [{}] {}",
            waiting.key,
            what.trim_end().replace('\n', "\n    ")
        ));
    }
    if answers {
        lines.push(format!(
            "Answer with: vpf-run answer {} <key> <answer> [--as <who>]",
            record.id
        ));
    }
    lines.push(format!("Then go on with: vpf-run go {}", record.id));
    lines.join("\n")
}

fn folder_of(arg: &FolderArg) -> Result<PathBuf, ExitCode> {
    arg.folder
        .clone()
        .map_or_else(std::env::current_dir, Ok)
        .map_err(|error| {
            eprintln!("vpf-run: cannot find the folder: {error}");
            ExitCode::from(2)
        })
}

/// Every run kept in the folder that can be read, by id.
fn kept_runs(folder: &Path) -> Vec<Record> {
    let Ok(read) = fs::read_dir(folder.join(".vpf").join("runs")) else {
        return Vec::new();
    };
    let mut files: Vec<PathBuf> = read
        .filter_map(Result::ok)
        .map(|entry| entry.path())
        .filter(|path| {
            path.extension()
                .is_some_and(|extension| extension == "json")
        })
        .collect();
    files.sort();
    files
        .iter()
        .filter_map(|file| Record::load(file).ok())
        .collect()
}

/// The one kept run whose id starts with `id`.
fn find_run(folder: &Path, id: &str) -> Result<Record, ExitCode> {
    let mut found: Vec<Record> = kept_runs(folder)
        .into_iter()
        .filter(|record| record.id.starts_with(id))
        .collect();
    match found.len() {
        1 => Ok(found.remove(0)),
        0 => {
            println!("No run here starts with {id}.");
            Err(ExitCode::from(1))
        }
        count => {
            println!("{count} runs start with {id}: say more of its id.");
            Err(ExitCode::from(1))
        }
    }
}

fn keep(record: &Record, folder: &Path) -> Result<(), ExitCode> {
    record.keep(folder).map(|_| ()).map_err(|error| {
        eprintln!("vpf-run: cannot keep the run {}: {error}", record.id);
        ExitCode::from(2)
    })
}

fn status(folder: &Path) -> ExitCode {
    let waiting: Vec<Record> = kept_runs(folder)
        .into_iter()
        .filter(|record| matches!(record.outcome, Outcome::Waiting(_)))
        .collect();
    if waiting.is_empty() {
        println!("No run waits.");
    }
    for record in &waiting {
        println!(
            "{} · {}: {}",
            record.id,
            record.plan.as_deref().unwrap_or("plan"),
            record.wish
        );
        println!("{}", self::waiting(record));
    }
    ExitCode::SUCCESS
}

/// The reply the words give to what is waited for.
fn reply_of(wait: &Wait, words: &[String], back: Option<&str>) -> Result<Reply, String> {
    let text = words.join(" ");
    let first = words
        .first()
        .map(|word| word.to_lowercase())
        .unwrap_or_default();
    match wait {
        Wait::Answer(_) => Ok(Reply::Text(text)),
        // `no>commit,tests: what is wrong` names the steps to send the work back to, as `--back` does.
        Wait::Approval(_) if first.starts_with("no>") => {
            let rest = &text[3..];
            let (ids, points) = rest.split_once(':').unwrap_or((rest, ""));
            let back = ids
                .split(',')
                .chain(back.unwrap_or_default().split([',', ' ']))
                .map(str::trim)
                .filter(|id| !id.is_empty())
                .map(str::to_owned)
                .collect();
            Ok(Reply::No {
                points: points.trim().to_owned(),
                back,
            })
        }
        Wait::Approval(_) | Wait::Decision(_) => match first.as_str() {
            "y" | "yes" => Ok(Reply::Yes),
            "n" | "no" => Ok(Reply::No {
                points: words[1..].join(" "),
                back: back
                    .unwrap_or_default()
                    .split([',', ' '])
                    .map(str::trim)
                    .filter(|id| !id.is_empty())
                    .map(str::to_owned)
                    .collect(),
            }),
            _ if matches!(wait, Wait::Approval(_)) => Err(
                "Answer yes, or no and what is wrong; to send the work back, add --back and the steps, or answer \
                 no>steps: what is wrong."
                    .to_owned(),
            ),
            _ => Err("Answer yes, or no and what is wrong.".to_owned()),
        },
        Wait::Choice { options, .. } => text
            .parse::<usize>()
            .ok()
            .and_then(|number| number.checked_sub(1))
            .filter(|chosen| *chosen < options.len())
            .or_else(|| options.iter().position(|option| *option == text))
            .map(Reply::Option)
            .ok_or_else(|| format!("Answer a number from 1 to {}.", options.len())),
        Wait::Time(_) => Err("This waits for a time, not for an answer.".to_owned()),
    }
}

fn answer(
    folder: &Path,
    id: &str,
    key: &str,
    words: &[String],
    by: Option<&str>,
    back: Option<&str>,
) -> ExitCode {
    let mut record = match find_run(folder, id) {
        Ok(record) => record,
        Err(code) => return code,
    };
    let Outcome::Waiting(list) = &record.outcome else {
        println!("The run {} waits for nothing.", record.id);
        return ExitCode::from(1);
    };
    let Some(waiting) = list.iter().find(|waiting| waiting.key == key) else {
        println!("The run {} does not wait for {key}.", record.id);
        return ExitCode::from(1);
    };
    let reply = match reply_of(&waiting.wait, words, back) {
        Ok(reply) => reply,
        Err(error) => {
            println!("{error}");
            return ExitCode::from(1);
        }
    };
    if let Err(error) = record.reply(key, reply, by) {
        println!("Not kept: {error}.");
        return ExitCode::from(1);
    }
    if let Err(code) = keep(&record, folder) {
        return code;
    }
    println!("Kept. Go on with: vpf-run go {}", record.id);
    ExitCode::SUCCESS
}

fn go(folder: &Path, id: Option<&str>, detach: bool, at_once: usize, agent_line: &str) -> ExitCode {
    let records = match id {
        Some(id) => match find_run(folder, id) {
            Ok(record) => vec![record],
            Err(code) => return code,
        },
        None => kept_runs(folder)
            .into_iter()
            .filter(|record| matches!(record.outcome, Outcome::Waiting(_)))
            .collect(),
    };
    if records.is_empty() {
        println!("No run waits.");
        return ExitCode::SUCCESS;
    }
    let stdin = io::stdin();
    let mut person = Terminal::new(BufReader::new(stdin.lock()), io::stdout());
    let mut code = 0;
    for record in records {
        if !matches!(record.outcome, Outcome::Waiting(_)) {
            println!("The run {} does not wait.", record.id);
            code = 1;
            continue;
        }
        let agent_line = if agent_line.trim().is_empty() {
            remembered_agent(folder, &record.id)
        } else {
            agent_line.to_owned()
        };
        if record
            .versions
            .last()
            .is_some_and(|version| needs_agent(&version.plan))
            && agent_line.trim().is_empty()
        {
            eprintln!(
                "vpf-run: the run {} needs an agent. Give the command that answers as one with --agent, or set VPF_AGENT_COMMAND.",
                record.id
            );
            return ExitCode::from(2);
        }
        let agent = CommandAgent::new(agent_line.clone());
        person.tell(&format!("Going on with {}: {}", record.id, record.wish));
        let mut keeper = AgentKeeper {
            folder,
            line: &agent_line,
        };
        let record = Runner::new(folder, &agent, &mut person)
            .keeper(&mut keeper)
            .plans_in(folder)
            .detach(detach)
            .at_once(at_once)
            .resume(&record);
        remember_agent(folder, &record, &agent_line);
        code = match (code, ended(&mut person, &record)) {
            (1, _) | (_, 1) => 1,
            (_, WAITING) | (WAITING, _) => WAITING,
            _ => 0,
        };
    }
    ExitCode::from(code)
}

fn change(folder: &Path, id: &str, file: &Path, approved_by: &str) -> ExitCode {
    let mut record = match find_run(folder, id) {
        Ok(record) => record,
        Err(code) => return code,
    };
    let plan = match load(file) {
        Ok(plan) => plan,
        Err(code) => return code,
    };
    if let Err(error) = record.change(&plan, approved_by, Timestamp::now()) {
        println!("Not taken: {error}.");
        return ExitCode::from(1);
    }
    if let Err(code) = keep(&record, folder) {
        return code;
    }
    let from = record
        .versions
        .last()
        .and_then(|version| version.from.clone())
        .map_or_else(String::new, |from| format!(" from the step {from}"));
    println!(
        "The run {} follows the new version{from}. Go on with: vpf-run go {}",
        record.id, record.id
    );
    ExitCode::SUCCESS
}

fn main() -> ExitCode {
    let cli = Cli::parse();
    match &cli.command {
        Some(Command::Status { folder }) => match folder_of(folder) {
            Ok(folder) => status(&folder),
            Err(code) => code,
        },
        Some(Command::Answer {
            run,
            key,
            reply,
            by,
            back,
            folder,
        }) => match folder_of(folder) {
            Ok(folder) => answer(&folder, run, key, reply, by.as_deref(), back.as_deref()),
            Err(code) => code,
        },
        Some(Command::Go {
            run,
            detach,
            at_once,
            folder,
            agent,
        }) => match folder_of(folder) {
            Ok(folder) => go(
                &folder,
                run.as_deref(),
                *detach,
                *at_once,
                agent.agent.as_deref().unwrap_or_default(),
            ),
            Err(code) => code,
        },
        Some(Command::Change {
            run,
            plan,
            approved_by,
            folder,
        }) => match folder_of(folder) {
            Ok(folder) => change(&folder, run, plan, approved_by),
            Err(code) => code,
        },
        None => start(&cli),
    }
}

/// Where the agent command a run started with is kept while the run waits, so that `go` goes on with it.
fn agent_file(folder: &Path, id: &str) -> PathBuf {
    folder.join(".vpf").join("agents").join(id)
}

/// Keeps the agent command of a run that waits, and forgets it once the run has ended.
fn remember_agent(folder: &Path, record: &Record, agent_line: &str) {
    let file = agent_file(folder, &record.id);
    if matches!(record.outcome, Outcome::Waiting(_)) && !agent_line.trim().is_empty() {
        let kept = file
            .parent()
            .map_or(Ok(()), fs::create_dir_all)
            .and_then(|()| fs::write(&file, agent_line));
        if let Err(error) = kept {
            eprintln!("vpf-run: the agent command could not be kept for `go`: {error}");
        }
    } else {
        let _ = fs::remove_file(file);
    }
}

/// Keeps the agent command of a run as soon as it begins, so that `go` goes on with it even when the run stopped
/// in the middle.
struct AgentKeeper<'a> {
    folder: &'a Path,
    line: &'a str,
}

impl Keeper for AgentKeeper<'_> {
    fn begin(&mut self, record: &Record) {
        let waiting = Record {
            outcome: Outcome::Waiting(Vec::new()),
            ..record.clone()
        };
        remember_agent(self.folder, &waiting, self.line);
    }

    fn kept(&mut self, _: &vpf_runner::Entry) {}
}

/// The agent command a waiting run started with, or nothing.
fn remembered_agent(folder: &Path, id: &str) -> String {
    fs::read_to_string(agent_file(folder, id)).unwrap_or_default()
}

/// Runs a plan file as its start says.
fn start(cli: &Cli) -> ExitCode {
    let Some(file) = &cli.plan else {
        eprintln!("vpf-run: name the plan to run.");
        return ExitCode::from(2);
    };
    let plan = match load(file) {
        Ok(plan) => plan,
        Err(code) => return code,
    };
    let agent_line = cli.agent.agent.clone().unwrap_or_default();
    if needs_agent(&plan) && agent_line.trim().is_empty() {
        eprintln!(
            "vpf-run: this plan needs an agent. Give the command that answers as one with --agent, or set VPF_AGENT_COMMAND."
        );
        return ExitCode::from(2);
    }
    let folder = match folder_of(&cli.folder) {
        Ok(folder) => folder,
        Err(code) => return code,
    };
    let plans = file
        .parent()
        .filter(|parent| !parent.as_os_str().is_empty())
        .map_or_else(|| PathBuf::from("."), Path::to_path_buf);
    let plans = std::path::absolute(&plans).unwrap_or(plans);
    let name = name_of(file);

    let stdin = io::stdin();
    let mut person = Terminal::new(BufReader::new(stdin.lock()), io::stdout());
    let agent = CommandAgent::new(agent_line.clone());
    let start = plan.start();

    let passed = passed_dates(&plan, Timestamp::now());
    if !passed.is_empty() {
        person.tell(&format!(
            "These dates of the plan have already passed: {}.",
            passed.join("; ")
        ));
    }

    let mut asked = cli.asked.clone();
    if asked.is_none() && start == Start::Asked && names_asked(&plan) {
        asked = person.answer(&vpf_runner::Ask {
            question: "What do you ask?".to_owned(),
            ..vpf_runner::Ask::default()
        });
        if asked.is_none() {
            println!("Stopped: nothing was asked.");
            return ExitCode::from(1);
        }
    }
    let asked = asked.unwrap_or_default();

    let mut run_once = |person: &mut dyn Person| {
        let wish = vpf_runner::fill(
            &plan.wish,
            &std::collections::HashMap::from([("asked".to_owned(), asked.clone())]),
        );
        person.tell(&format!("Running {name}: {wish}"));
        let mut keeper = AgentKeeper {
            folder: &folder,
            line: &agent_line,
        };
        let record = Runner::new(&folder, &agent, person)
            .keeper(&mut keeper)
            .plans_in(&plans)
            .keep_records(&name)
            .detach(cli.detach)
            .at_once(cli.at_once)
            .run(&plan, &asked);
        remember_agent(&folder, &record, agent_line.as_str());
        ended(person, &record)
    };
    let poll = Duration::from_millis(cli.poll_ms.max(10));
    let most = cli.runs.unwrap_or(u32::MAX);
    ExitCode::from(serve(
        &plan,
        most,
        poll,
        &folder,
        &mut person,
        &mut run_once,
    ))
}