turnframe-runtime 0.1.2

Deterministic turn orchestration runtime for Turnframe: interpretation, reduction, interactions, commands, events and response composition
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
//! What a turn did, gathered by code into the one document the acknowledgement is
//! written from, with the single thing to ask for next.

use serde::Serialize;
use turnframe_core::case::{CaseKey, CaseRef};
use turnframe_core::event::OperationalReceipt;
use turnframe_core::flow::ErasedWorkflowView;
use turnframe_core::interaction::Interaction;
use turnframe_core::locale::{Locale, LocalizedText};
use turnframe_core::response::{CaseLabel, Expectation, NarratableFact};

/// The turn as the acknowledgement may state it.
#[derive(Debug, Clone, Default, PartialEq, Serialize)]
pub(crate) struct TurnOutcome {
    /// What was done, each as its receipt says it.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub done: Vec<String>,
    /// What was not done, each with its reason.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub not_done: Vec<String>,
    /// What the user said the assistant got wrong.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub disputes: Vec<String>,
    /// Workflows the turn started without writing anything yet.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub starting: Vec<String>,
    /// The one thing to ask for next.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ask: Option<Ask>,
    /// The card on screen, when there is one.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub card: Option<String>,
    /// What the user may do next, when the record needs nothing more.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub next: Vec<String>,
    /// The question a reply ends on when nothing is asked, no card is on screen and nothing
    /// comes next: no reply leaves the user without a way forward.
    #[serde(skip)]
    pub closing: Option<String>,
}

impl TurnOutcome {
    /// Whether there is nothing to say: then no acknowledgement is written at all.
    pub fn is_silent(&self) -> bool {
        self.done.is_empty()
            && self.not_done.is_empty()
            && self.disputes.is_empty()
            && self.starting.is_empty()
            && self.ask.is_none()
            && self.card.is_none()
            && self.next.is_empty()
    }

    /// Whether all the reply has to say is what it asks next.
    pub fn only_asks(&self) -> bool {
        self.ask.is_some()
            && self.done.is_empty()
            && self.not_done.is_empty()
            && self.disputes.is_empty()
            && self.starting.is_empty()
            && self.card.is_none()
            && self.next.is_empty()
    }
}

/// The one thing the reply asks for, chosen by code.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub(crate) struct Ask {
    /// The record it is about, by its label.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub record: Option<String>,
    /// What to ask for: the argument's words or the obligation's sentence.
    pub what: String,
    /// Why the value is needed again, when the domain refused the one given.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub because: Option<String>,
    /// The question the reply asks when no model writes one, and the model rewords.
    pub question: String,
    /// Whether it is about a record the turn did not reach, so the question names it.
    #[serde(skip)]
    pub elsewhere: bool,
    /// What the next turn expects, recorded once the reply is out.
    #[serde(skip)]
    pub expectation: Option<Expectation>,
}

/// Copy for the questions code writes when no acknowledgement does.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct AskCopy {
    /// A missing value; `{what}` is replaced by its label.
    pub value: LocalizedText,
    /// A value the domain refused; `{what}` is its label, `{because}` the reason.
    pub refused_value: LocalizedText,
    /// An open obligation the workflow gave no sentence; `{what}` is its name.
    pub obligation: LocalizedText,
    /// A receipt the user contested; `{what}` is the receipt as it was shown.
    pub contested: LocalizedText,
    /// A question about a record the turn did not reach; `{record}` is its label and
    /// `{question}` the question.
    pub elsewhere: LocalizedText,
    /// The question a reply ends on when it asks nothing else.
    pub go_on: LocalizedText,
}

impl AskCopy {
    /// The built-in copy: English, with Italian.
    #[must_use]
    pub fn standard() -> Self {
        crate::copy::ServerCopy::translated(Self::english(), "it", ITALIAN)
    }

    /// English alone.
    #[must_use]
    pub fn english() -> Self {
        Self {
            value: LocalizedText::new("What should the {what} be?"),
            refused_value: LocalizedText::new("{because} What should the {what} be instead?"),
            obligation: LocalizedText::new("Still needed: {what}."),
            contested: LocalizedText::new("{what} What should it be instead?"),
            elsewhere: LocalizedText::new("{record}: {question}"),
            go_on: LocalizedText::new("What would you like to do next?"),
        }
    }
}

impl Default for AskCopy {
    fn default() -> Self {
        Self::standard()
    }
}

crate::copy::server_copy!(
    AskCopy,
    [
        value,
        refused_value,
        obligation,
        contested,
        elsewhere,
        go_on
    ]
);

/// The built-in Italian of [`AskCopy`], by field.
const ITALIAN: &[(&str, &str)] = &[
    ("value", "Che cosa metto come {what}?"),
    (
        "refused_value",
        "{because} Che cosa metto come {what}, invece?",
    ),
    ("obligation", "Manca ancora: {what}."),
    ("contested", "{what} Come dovrebbe essere, invece?"),
    ("elsewhere", "{record}: {question}"),
    ("go_on", "Cosa vuoi fare adesso?"),
];

fn fill(template: &LocalizedText, locale: &Locale, pairs: &[(&str, &str)]) -> String {
    let mut text = template.resolve(locale).to_owned();
    for (key, value) in pairs {
        text = text.replace(&format!("{{{key}}}"), value);
    }
    text.trim().to_owned()
}

/// What an outcome is gathered from.
pub(crate) struct Material<'a> {
    pub receipts: &'a [OperationalReceipt],
    pub facts: &'a [NarratableFact],
    pub interactions: &'a [Interaction],
    pub views: &'a [ErasedWorkflowView],
    /// The cases an act of this turn reached, in act order.
    pub touched: &'a [CaseKey],
    /// Other cases in view, asked about once the touched ones need nothing.
    pub beside: &'a [CaseKey],
    pub labels: &'a [CaseLabel],
    pub disputes: &'a [String],
    pub started: &'a [turnframe_core::ids::WorkflowKey],
    pub contested: &'a [String],
    /// What each case lets the user do next once it owes nothing, by case.
    pub next_steps: &'a [(CaseKey, Vec<LocalizedText>)],
    pub locale: &'a Locale,
    pub copy: &'a AskCopy,
}

impl Material<'_> {
    fn label(&self, case_ref: &CaseRef) -> Option<String> {
        self.labels
            .iter()
            .find(|label| label.case_ref.key() == case_ref.key())
            .map(|label| label.label.clone())
    }

    /// A receipt the user contested, else the first value an act is waiting for, else
    /// the first open obligation of a record the turn touched. A card on a record the turn
    /// reached is what comes next, so no obligation is asked beside it.
    fn ask(&self) -> Option<Ask> {
        if let Some(contested) = self.contested.first() {
            return Some(Ask {
                record: None,
                what: contested.clone(),
                because: None,
                question: fill(&self.copy.contested, self.locale, &[("what", contested)]),
                elsewhere: false,
                expectation: None,
            });
        }
        let waiting = self.facts.iter().find_map(|fact| match fact {
            NarratableFact::ValueNeeded {
                case_ref,
                arguments,
                reason,
                ..
            } => Some((case_ref.clone(), arguments.join(", "), reason.clone())),
            _ => None,
        });
        if let Some((case_ref, what, because)) = waiting {
            let question = match &because {
                Some(because) => fill(
                    &self.copy.refused_value,
                    self.locale,
                    &[("what", &what), ("because", because)],
                ),
                None => fill(&self.copy.value, self.locale, &[("what", &what)]),
            };
            return Some(Ask {
                record: case_ref.as_ref().and_then(|case_ref| self.label(case_ref)),
                what,
                because,
                question,
                elsewhere: false,
                // The waiting act is recorded as its own expectation already.
                expectation: None,
            });
        }
        let reached = |case_ref: &CaseRef| self.touched.contains(&case_ref.key());
        let card_next = self
            .interactions
            .iter()
            .any(|card| card.blocking && reached(&card.case_ref))
            || self
                .views
                .iter()
                .any(|view| view.blocking_interaction.is_some() && reached(&view.case_ref));
        if card_next {
            return None;
        }
        let (view, obligation) = self.touched.iter().chain(self.beside).find_map(|key| {
            let view = self.views.iter().find(|view| view.case_ref.key() == *key)?;
            Some((view, view.obligations.first()?))
        })?;
        // The workflow's sentence is the question; without one, its name is read out.
        let (what, question) = match &obligation.sentence {
            Some(sentence) => {
                let sentence = sentence.resolve(self.locale).to_owned();
                (sentence.clone(), sentence)
            }
            None => {
                let what = obligation_words(&obligation.value);
                let question = fill(&self.copy.obligation, self.locale, &[("what", &what)]);
                (what, question)
            }
        };
        // An obligation whose workflow names the act that answers it is awaited as that
        // act, so a bare answer completes it.
        let expectation = match &obligation.act {
            Some(act) => Expectation::AwaitingOperation {
                case_ref: view.case_ref.clone(),
                obligation: what.clone(),
                act: act.clone(),
            },
            None => Expectation::AwaitingObligation {
                case_ref: view.case_ref.clone(),
                obligation: what.clone(),
            },
        };
        let record = self.label(&view.case_ref);
        // A record the turn did not reach is not the one the reply talks about: name it.
        let elsewhere = !reached(&view.case_ref) && record.is_some();
        let question = match record.as_deref().filter(|_| elsewhere) {
            Some(label) => fill(
                &self.copy.elsewhere,
                self.locale,
                &[("record", label), ("question", &question)],
            ),
            None => question,
        };
        Some(Ask {
            record,
            question,
            elsewhere,
            expectation: Some(expectation),
            what,
            because: None,
        })
    }

    /// Gathers the outcome.
    pub fn outcome(&self) -> TurnOutcome {
        let locale = self.locale;
        let done = self
            .receipts
            .iter()
            .map(|receipt| {
                format!(
                    "{}: {}",
                    receipt.title.resolve(locale),
                    receipt.body.resolve(locale)
                )
            })
            .collect();
        let not_done = self.facts.iter().filter_map(not_done).collect();
        let card = self.interactions.first().map(|card| {
            let options: Vec<&str> = card
                .payload
                .options
                .iter()
                .map(|option| option.label.resolve(locale))
                .collect();
            let about = self
                .touched
                .contains(&card.case_ref.key())
                .then(|| self.label(&card.case_ref))
                .flatten()
                .map(|label| format!("{label}: "))
                .unwrap_or_default();
            format!(
                "{about}{} ({})",
                card.payload.title.resolve(locale),
                options.join(" / ")
            )
        });
        let ask = self.ask();
        let next = if ask.is_none() && card.is_none() {
            self.touched
                .iter()
                .find_map(|key| {
                    self.next_steps
                        .iter()
                        .find(|(case, steps)| case == key && !steps.is_empty())
                })
                .map(|(_, steps)| {
                    steps
                        .iter()
                        .map(|step| step.resolve(locale).to_owned())
                        .collect()
                })
                .unwrap_or_default()
        } else {
            Vec::new()
        };
        let closing = (ask.is_none() && card.is_none() && next.is_empty())
            .then(|| self.copy.go_on.resolve(locale).to_owned());
        TurnOutcome {
            done,
            not_done,
            disputes: self.disputes.to_vec(),
            starting: self.started.iter().map(ToString::to_string).collect(),
            ask,
            card,
            next,
            closing,
        }
    }
}

/// An obligation's name in words: a string, or an object's one tag, with its
/// underscores read as spaces.
fn obligation_words(value: &serde_json::Value) -> String {
    let name = match value {
        serde_json::Value::String(name) => Some(name.as_str()),
        serde_json::Value::Object(map) => map.keys().next().map(String::as_str),
        _ => None,
    };
    name.map_or_else(|| value.to_string(), |name| name.replace('_', " "))
}

/// What a fact says was not done, and why, as a sentence the reply may restate.
fn not_done(fact: &NarratableFact) -> Option<String> {
    Some(match fact {
        NarratableFact::ActRefused {
            explanation, code, ..
        } => {
            if explanation.is_empty() {
                format!("Refused ({code}).")
            } else {
                explanation.clone()
            }
        }
        NarratableFact::ActChangedNothing { explanation, .. } if !explanation.is_empty() => {
            explanation.clone()
        }
        NarratableFact::ActChangedNothing { operation, .. } => format!(
            "Nothing changed: {} was already so.",
            operation.as_deref().unwrap_or("what was asked")
        ),
        NarratableFact::InstructionDeclined {
            question,
            option_label,
            ..
        } => format!("The user answered «{question}» with «{option_label}»."),
        NarratableFact::ActHeld { operation, because } => {
            format!("{operation} waits: «{because}» was not understood.")
        }
        NarratableFact::NotUnderstood { words } => format!("Not understood: «{words}»."),
        NarratableFact::WorkflowUnavailable { reason, .. } => reason.clone(),
        NarratableFact::AttachmentNotShown {
            filename, reason, ..
        } => format!(
            "The file {} was not read: {reason}",
            filename.as_deref().unwrap_or("attached")
        ),
        _ => return None,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use turnframe_core::ids::CaseRevision;

    fn material<'a>(
        facts: &'a [NarratableFact],
        copy: &'a AskCopy,
        locale: &'a Locale,
    ) -> Material<'a> {
        Material {
            receipts: &[],
            facts,
            interactions: &[],
            views: &[],
            touched: &[],
            beside: &[],
            labels: &[],
            disputes: &[],
            started: &[],
            contested: &[],
            next_steps: &[],
            locale,
            copy,
        }
    }

    #[test]
    fn a_record_that_needs_nothing_more_offers_its_next_steps() {
        let view = |obligations| ErasedWorkflowView {
            case_ref: CaseRef::new("sample", "s-1", CaseRevision(1)),
            workflow_version: turnframe_core::ids::WorkflowVersion::from("1"),
            phase: serde_json::json!("collecting"),
            phase_ownership: turnframe_core::flow::PhaseOwnership::User,
            obligations,
            blocking_interaction: None,
            notices: Vec::new(),
            outcome: None,
            state: Vec::new(),
        };
        let owed = turnframe_core::flow::ErasedObligation {
            id: turnframe_core::flow::ObligationId("\"a\"".to_owned()),
            value: serde_json::json!("a"),
            sentence: Some(LocalizedText::new("What is A?")),
            act: None,
        };
        let copy = AskCopy::english();
        let locale = Locale::from("en-GB");
        let touched = [CaseRef::new("sample", "s-1", CaseRevision(1)).key()];
        let next_steps = [(
            touched[0].clone(),
            vec![
                LocalizedText::new("Add another item."),
                LocalizedText::new("Send it."),
            ],
        )];

        let complete = [view(Vec::new())];
        let mut material = material(&[], &copy, &locale);
        material.views = &complete;
        material.touched = &touched;
        material.next_steps = &next_steps;
        let outcome = material.outcome();
        assert_eq!(outcome.ask, None);
        assert_eq!(outcome.next, vec!["Add another item.", "Send it."]);

        let open = [view(vec![owed])];
        material.views = &open;
        let outcome = material.outcome();
        assert!(outcome.ask.is_some());
        assert!(outcome.next.is_empty(), "what is owed comes first");
    }

    #[test]
    fn a_waiting_value_is_the_ask_and_code_writes_its_question() {
        let facts = [NarratableFact::ValueNeeded {
            case_ref: Some(CaseRef::new("trip", "trip-1", CaseRevision(1))),
            operation: "trip.set_name".to_owned(),
            arguments: vec!["subject".to_owned()],
            reason: None,
        }];
        let copy = AskCopy::english();
        let locale = Locale::from("en-GB");
        let outcome = material(&facts, &copy, &locale).outcome();
        let ask = outcome.ask.expect("an ask");
        assert_eq!(ask.what, "subject");
        assert_eq!(ask.question, "What should the subject be?");
        assert!(
            outcome.not_done.is_empty(),
            "a missing value is asked for, not reported"
        );
    }

    #[test]
    fn an_obligation_without_a_sentence_is_never_asked_by_its_code() {
        let case_ref = CaseRef::new("trip", "trip-2", CaseRevision(1));
        let view = ErasedWorkflowView {
            case_ref: case_ref.clone(),
            workflow_version: turnframe_core::ids::WorkflowVersion::from("1"),
            phase: serde_json::json!("collecting"),
            phase_ownership: turnframe_core::flow::PhaseOwnership::User,
            obligations: vec![turnframe_core::flow::ErasedObligation {
                id: turnframe_core::flow::ObligationId("\"select_traveler\"".to_owned()),
                value: serde_json::json!("select_traveler"),
                sentence: None,
                act: None,
            }],
            blocking_interaction: None,
            notices: Vec::new(),
            outcome: None,
            state: Vec::new(),
        };
        let copy = AskCopy::english();
        let locale = Locale::from("en-GB");
        let views = [view];
        let touched = [case_ref.key()];
        let mut material = material(&[], &copy, &locale);
        material.views = &views;
        material.touched = &touched;
        let ask = material
            .outcome()
            .ask
            .expect("the open obligation is asked for");
        assert_eq!(ask.question, "Still needed: select traveler.");
    }

    #[test]
    fn a_card_on_screen_is_what_comes_next() {
        let obligation = |case_id: &str, requirement| ErasedWorkflowView {
            case_ref: CaseRef::new("sample", case_id, CaseRevision(1)),
            workflow_version: turnframe_core::ids::WorkflowVersion::from("1"),
            phase: serde_json::json!("collecting"),
            phase_ownership: turnframe_core::flow::PhaseOwnership::User,
            obligations: vec![turnframe_core::flow::ErasedObligation {
                id: turnframe_core::flow::ObligationId("\"a\"".to_owned()),
                value: serde_json::json!("a"),
                sentence: Some(LocalizedText::new("What is A?")),
                act: None,
            }],
            blocking_interaction: requirement,
            notices: Vec::new(),
            outcome: None,
            state: Vec::new(),
        };
        let carded = obligation(
            "s-1",
            Some(turnframe_core::flow::InteractionRequirement::blocking(
                "confirm",
                turnframe_core::interaction::InteractionKind::Boolean,
            )),
        );
        let other = obligation("s-2", None);
        let touched = [carded.case_ref.key()];
        let beside = [other.case_ref.key()];
        let views = [carded, other];
        let copy = AskCopy::english();
        let locale = Locale::from("en-GB");
        let mut material = material(&[], &copy, &locale);
        material.views = &views;
        material.touched = &touched;
        material.beside = &beside;
        assert_eq!(material.outcome().ask, None);
    }

    fn owing(case_id: &str, owed: bool) -> ErasedWorkflowView {
        ErasedWorkflowView {
            case_ref: CaseRef::new("sample", case_id, CaseRevision(1)),
            workflow_version: turnframe_core::ids::WorkflowVersion::from("1"),
            phase: serde_json::json!("collecting"),
            phase_ownership: turnframe_core::flow::PhaseOwnership::User,
            obligations: owed
                .then(|| turnframe_core::flow::ErasedObligation {
                    id: turnframe_core::flow::ObligationId("\"a\"".to_owned()),
                    value: serde_json::json!("a"),
                    sentence: Some(LocalizedText::new("What is A?")),
                    act: None,
                })
                .into_iter()
                .collect(),
            blocking_interaction: None,
            notices: Vec::new(),
            outcome: None,
            state: Vec::new(),
        }
    }

    #[test]
    fn an_obligation_of_a_record_the_turn_did_not_reach_names_that_record() {
        let views = [owing("s-1", false), owing("s-2", true)];
        let touched = [views[0].case_ref.key()];
        let beside = [views[1].case_ref.key()];
        let labels = [CaseLabel {
            case_ref: views[1].case_ref.clone(),
            label: "Sample 2".to_owned(),
        }];
        let copy = AskCopy::english();
        let locale = Locale::from("en-GB");
        let mut material = material(&[], &copy, &locale);
        material.views = &views;
        material.touched = &touched;
        material.beside = &beside;
        material.labels = &labels;
        let ask = material
            .outcome()
            .ask
            .expect("the other record's obligation");
        assert!(ask.elsewhere);
        assert_eq!(ask.question, "Sample 2: What is A?");
    }

    #[test]
    fn an_obligation_of_a_record_the_turn_reached_is_asked_as_written() {
        let views = [owing("s-1", true)];
        let touched = [views[0].case_ref.key()];
        let copy = AskCopy::english();
        let locale = Locale::from("en-GB");
        let mut material = material(&[], &copy, &locale);
        material.views = &views;
        material.touched = &touched;
        let ask = material.outcome().ask.expect("its obligation");
        assert!(!ask.elsewhere);
        assert_eq!(ask.question, "What is A?");
    }

    #[test]
    fn nothing_to_say_is_silence() {
        let copy = AskCopy::english();
        let locale = Locale::from("en-GB");
        assert!(material(&[], &copy, &locale).outcome().is_silent());
    }
}