toha 0.4.1

Generate projects and files from templates through one interview for people, scripts, agents, and Rust callers.
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
// ---
// relationships:
//   implements: architecture
// ---
//! The update replay adapter.
//!
//! An update does not reuse the staged-replay walk, which treats a rejected
//! recorded answer as fatal, submits recorded batches whole, and cannot override
//! an answer. This adapter drives the unchanged interview engine from the base
//! application's recorded submissions: it turns them into a per-id queue in recorded
//! order (so a looped question replays its values in order), applies the route's
//! overrides first, and for each pending batch takes the next queued value for
//! every question, submitting when every required question has one. A recorded
//! value the new version rejects is removed and the question treated as
//! unanswered, with the rejection kept for the message. At the first batch it
//! cannot complete it hands the batch to the route, whose defaults are the
//! recorded raw values. `--reanswer` skips the auto-submission entirely.

use std::collections::{HashMap, VecDeque};

use indexmap::IndexMap;

use crate::interview::{
    AnswerError, CheckError, Completed, Ended, EvalError, Interview, Item, Pending, RawAnswer,
    RawAnswers, Rejections, Seed,
};
use crate::template::{Id, Template};

/// The outcome of driving the interview from recorded submissions.
#[allow(clippy::large_enum_variant)]
pub(crate) enum Replay<'a> {
    /// The interview completed; `submissions` are the raw values actually
    /// submitted, in batch order, for the new application to record.
    Completed {
        completed: Completed,
        submissions: Vec<IndexMap<Id, RawAnswer>>,
    },
    /// The first batch replay could not complete. The route takes over: the
    /// person is prompted with the recorded values as defaults; the script route
    /// reports `questions`; the agent route stages the interview. `submissions`
    /// are the batches auto-submitted before this one, in order, which a staged
    /// update records so a resume replays them.
    Ask {
        pending: Box<Pending<'a>>,
        rejections: Rejections,
        submissions: Vec<IndexMap<Id, RawAnswer>>,
    },
    /// A flow `stop`/`abort` ended the interview.
    Ended(Ended),
}

/// Build the per-id value queue from the base's `recorded` submissions, in
/// recorded order, so a later submission's value for an id queues behind an
/// earlier one (a recording that carries more than one value for an id replays
/// them front to back).
fn build_queue(recorded: &[IndexMap<Id, RawAnswer>]) -> HashMap<Id, VecDeque<RawAnswer>> {
    let mut queue: HashMap<Id, VecDeque<RawAnswer>> = HashMap::new();
    for submission in recorded {
        for (id, raw) in submission {
            queue.entry(id.clone()).or_default().push_back(raw.clone());
        }
    }
    queue
}

/// Consume the queue for a staged submission this template already accepted: pop
/// the front recorded value of each answered id, so a value a staged batch used
/// is not offered again when `drive_from_queue` continues at a later batch. Ids
/// the queue does not hold (unrelated or already drained) are left untouched.
fn consume_staged(
    queue: &mut HashMap<Id, VecDeque<RawAnswer>>,
    staged_sub: &IndexMap<Id, RawAnswer>,
) {
    for id in staged_sub.keys() {
        if let Some(values) = queue.get_mut(id) {
            values.pop_front();
        }
    }
}

/// Drive the interview for an update from the base's `recorded` submissions, with
/// route `overrides` (already verified) applied first. `seed` carries the frozen
/// instant and context; its defaults are set here to the recorded/override
/// values so the route falls back to them.
pub(crate) fn replay<'a>(
    template: &'a Template,
    seed: Seed,
    recorded: &[IndexMap<Id, RawAnswer>],
    overrides: RawAnswers,
    reanswer: bool,
) -> Result<Replay<'a>, EvalError> {
    replay_resume_with_overrides(template, seed, recorded, &[], &overrides, reanswer)
}

/// Recorded values with explicit overrides first and configured presets last.
/// Both replay and the uncovered-question projection consume this same queue.
fn update_queue(
    recorded: &[RawAnswers],
    overrides: &RawAnswers,
    presets: &RawAnswers,
) -> HashMap<Id, VecDeque<RawAnswer>> {
    let mut queue = build_queue(recorded);
    for (id, raw) in overrides {
        queue.insert(id.clone(), VecDeque::from([raw.clone()]));
    }
    for (id, raw) in presets {
        queue
            .entry(id.clone())
            .or_insert_with(|| VecDeque::from([raw.clone()]));
    }
    queue
}

/// Resume a staged update: rebuild the adapter from the base's `recorded`
/// submissions, replay the `staged` submissions this template already accepted
/// (popping each answered id from the queue), then continue at the pending batch.
/// The seed carries the frozen instant, context, and configured presets.
pub(crate) fn replay_resume<'a>(
    template: &'a Template,
    seed: Seed,
    recorded: &[RawAnswers],
    staged: &[RawAnswers],
    reanswer: bool,
) -> Result<Replay<'a>, EvalError> {
    replay_resume_with_overrides(
        template,
        seed,
        recorded,
        staged,
        &RawAnswers::new(),
        reanswer,
    )
}

fn replay_resume_with_overrides<'a>(
    template: &'a Template,
    mut seed: Seed,
    recorded: &[RawAnswers],
    staged: &[RawAnswers],
    overrides: &RawAnswers,
    reanswer: bool,
) -> Result<Replay<'a>, EvalError> {
    let mut queue = update_queue(recorded, overrides, &seed.defaults);
    // Keep the same precedence in prompt defaults as in the replay queue.
    for submission in recorded {
        seed.defaults.extend(submission.clone());
    }
    seed.defaults.extend(overrides.clone());

    let mut interview = Interview::start(template, seed)?;
    let mut submissions = Vec::new();
    // Replay the staged submissions already accepted, consuming the queue so a
    // recorded value a staged batch already used is not offered again when
    // `drive_from_queue` continues at a later pending batch.
    for staged_sub in staged {
        // Admission has already supplied these documents to the pure engine.
        // Keep their session record, but do not submit them a second time.
        let replayed: RawAnswers = staged_sub.iter().filter(|(id, _)| {
            !matches!(template.question(id).map(|q| &q.kind), Some(crate::template::QuestionKind::Document { contract }) if contract.admitted().is_some())
        }).map(|(id, raw)| (id.clone(), raw.clone())).collect();
        if replayed.is_empty() {
            submissions.push(staged_sub.clone());
            continue;
        }
        let pending = match interview {
            Interview::Asking(pending) => pending,
            // A staged submission past completion cannot occur; stop if it does.
            other => {
                interview = other;
                break;
            }
        };
        consume_staged(&mut queue, staged_sub);
        interview = match pending.answer(replayed) {
            Ok(next) => {
                submissions.push(staged_sub.clone());
                next
            }
            Err(AnswerError::Rejected {
                pending,
                rejections,
            }) => {
                return Ok(Replay::Ask {
                    pending: Box::new(pending),
                    rejections,
                    submissions,
                });
            }
            Err(AnswerError::Eval(error)) => return Err(error),
        };
    }
    drive_from_queue(
        interview,
        queue,
        template.part_question().map(|q| &q.id),
        reanswer,
        submissions,
    )
}

/// Drive `interview` from the value `queue`, auto-submitting each batch when every
/// required question has a queued value and handing the first batch it cannot
/// complete (or, under `reanswer`, every batch) to the route. `submissions`
/// accumulates the batches submitted, in order.
fn drive_from_queue<'a>(
    mut interview: Interview<'a>,
    mut queue: HashMap<Id, VecDeque<RawAnswer>>,
    part_question: Option<&Id>,
    reanswer: bool,
    mut submissions: Vec<IndexMap<Id, RawAnswer>>,
) -> Result<Replay<'a>, EvalError> {
    loop {
        let pending = match interview {
            Interview::Complete(completed) => {
                return Ok(Replay::Completed {
                    completed,
                    submissions,
                });
            }
            Interview::Ended(ended) => return Ok(Replay::Ended(ended)),
            Interview::Asking(pending) => pending,
        };

        // `--reanswer` offers every batch to the route with the recorded defaults.
        if reanswer {
            return Ok(Replay::Ask {
                pending: Box::new(pending),
                rejections: Vec::new(),
                submissions,
            });
        }

        // A part question needs an explicit selection, including an empty one.
        // Do not accept its default merely because it is optional and absent
        // from the recorded revision.
        let prompts: Vec<(Id, bool)> = pending
            .batch()
            .items
            .iter()
            .filter_map(|item| match item {
                Item::Prompt(prompt) => Some((
                    prompt.id.clone(),
                    prompt.constraints.required || part_question == Some(&prompt.id),
                )),
                Item::Message(_) => None,
            })
            .collect();

        let mut raw: RawAnswers = IndexMap::new();
        let mut rejections = Rejections::new();
        let mut complete = true;
        for (id, required) in &prompts {
            match queue.get(id).and_then(|values| values.front()).cloned() {
                Some(value) => match pending.check(id, value.clone()) {
                    Ok(_) => {
                        raw.insert(id.clone(), value);
                    }
                    Err(CheckError::Rejected(rejection)) => {
                        rejections.push(rejection);
                        if let Some(values) = queue.get_mut(id) {
                            values.pop_front();
                        }
                        if *required {
                            complete = false;
                        }
                    }
                    Err(CheckError::Eval(error)) => return Err(error),
                },
                None => {
                    if *required {
                        complete = false;
                    }
                }
            }
        }

        if !complete {
            return Ok(Replay::Ask {
                pending: Box::new(pending),
                rejections,
                submissions,
            });
        }

        // Consume the queued values this batch used, then submit it. The batch is
        // recorded only once the engine accepts it.
        for id in raw.keys() {
            if let Some(values) = queue.get_mut(id) {
                values.pop_front();
            }
        }
        match pending.answer(raw.clone()) {
            Ok(next) => {
                submissions.push(raw);
                interview = next;
            }
            Err(AnswerError::Rejected {
                pending,
                rejections,
            }) => {
                return Ok(Replay::Ask {
                    pending: Box::new(pending),
                    rejections,
                    submissions,
                });
            }
            Err(AnswerError::Eval(error)) => return Err(error),
        }
    }
}

/// The outcome of driving an update interview, for a crate caller and the
/// command driver: the three cases of the crate-private adapter, carried over
/// already-public interview types. The adapter itself ([`Replay`], [`replay`])
/// stays crate-private; this is the seam a driver consumes.
#[allow(clippy::large_enum_variant)]
pub enum UpdateDrive<'a> {
    /// The interview completed; `submissions` are the raw values actually
    /// submitted, in batch order, for the new application to record.
    Completed {
        completed: Completed,
        submissions: Vec<IndexMap<Id, RawAnswer>>,
    },
    /// The first batch the replay could not complete. The route takes over: the
    /// person is prompted with the recorded values as defaults; the script route
    /// reports `questions`; the agent route stages the interview. `submissions`
    /// are the batches submitted before this one, which a staged update records.
    Ask {
        pending: Pending<'a>,
        rejections: Rejections,
        /// The batches submitted before this one, which a staged update records.
        submissions: Vec<IndexMap<Id, RawAnswer>>,
    },
    /// A flow `stop`/`abort` ended the interview.
    Ended(Ended),
}

/// Drive an update interview from a base application's `recorded` submissions, with
/// the route's `overrides` applied first and `reanswer` handing every batch to
/// the route. This is the driver-facing seam over the crate-private replay
/// adapter: it keeps the adapter's queue mechanics internal and returns the
/// typed outcome the person, script, and agent routes branch on.
pub fn drive_update<'a>(
    template: &'a Template,
    seed: Seed,
    recorded: &[IndexMap<Id, RawAnswer>],
    overrides: RawAnswers,
    reanswer: bool,
) -> Result<UpdateDrive<'a>, EvalError> {
    Ok(
        match replay(template, seed, recorded, overrides, reanswer)? {
            Replay::Completed {
                completed,
                submissions,
            } => UpdateDrive::Completed {
                completed,
                submissions,
            },
            Replay::Ask {
                pending,
                rejections,
                submissions,
            } => UpdateDrive::Ask {
                pending: *pending,
                rejections,
                submissions,
            },
            Replay::Ended(ended) => UpdateDrive::Ended(ended),
        },
    )
}

/// Resume a staged update interview: rebuild the adapter from the base's
/// `recorded` submissions, replay the `staged` submissions already accepted, and
/// continue at the pending batch. The driver-facing seam for `continue PATH` and
/// `apply PATH` on an update record.
pub fn drive_update_resume<'a>(
    template: &'a Template,
    seed: Seed,
    recorded: &[IndexMap<Id, RawAnswer>],
    staged: &[IndexMap<Id, RawAnswer>],
    reanswer: bool,
) -> Result<UpdateDrive<'a>, EvalError> {
    into_update_drive(replay_resume(template, seed, recorded, staged, reanswer))
}

pub(crate) fn drive_update_resume_with_overrides<'a>(
    template: &'a Template,
    seed: Seed,
    recorded: &[RawAnswers],
    staged: &[RawAnswers],
    overrides: &RawAnswers,
    reanswer: bool,
) -> Result<UpdateDrive<'a>, EvalError> {
    into_update_drive(replay_resume_with_overrides(
        template, seed, recorded, staged, overrides, reanswer,
    ))
}

fn into_update_drive(result: Result<Replay<'_>, EvalError>) -> Result<UpdateDrive<'_>, EvalError> {
    Ok(match result? {
        Replay::Completed {
            completed,
            submissions,
        } => UpdateDrive::Completed {
            completed,
            submissions,
        },
        Replay::Ask {
            pending,
            rejections,
            submissions,
        } => UpdateDrive::Ask {
            pending: *pending,
            rejections,
            submissions,
        },
        Replay::Ended(ended) => UpdateDrive::Ended(ended),
    })
}

#[cfg(test)]
mod tests;

/// Recorded values that can settle the current batch. The owned application
/// driver uses this view to omit covered form fields while using this same
/// queue and validator to submit their values beside a caller's new answers.
pub(crate) fn covered_answers(
    pending: &Pending<'_>,
    recorded: &[RawAnswers],
    accepted: &[RawAnswers],
    overrides: &RawAnswers,
    presets: &RawAnswers,
    reanswer: bool,
) -> Result<RawAnswers, EvalError> {
    if reanswer {
        return Ok(RawAnswers::new());
    }
    let mut queue = update_queue(recorded, overrides, presets);
    for submission in accepted {
        consume_staged(&mut queue, submission);
    }
    let mut covered = RawAnswers::new();
    for item in &pending.batch().items {
        let Item::Prompt(prompt) = item else {
            continue;
        };
        let Some(raw) = queue
            .get(&prompt.id)
            .and_then(|values| values.front())
            .cloned()
        else {
            continue;
        };
        match pending.check(&prompt.id, raw.clone()) {
            Ok(_) => {
                covered.insert(prompt.id.clone(), raw);
            }
            Err(CheckError::Rejected(_)) => {}
            Err(CheckError::Eval(error)) => return Err(error),
        }
    }
    Ok(covered)
}