tilo-actions 0.5.0

The Tilo action model: resources, the actions on them, and their registry, with the plain resource vocabulary that needs no store, search index entries included.
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
//! What an actor's step is, as data: which kind of work it does, and on what.
//!
//! One vocabulary for every surface that says what a step is at — the line
//! beside an actor's face, the people list, the card drawn in the window the
//! step happens in, the words a reviewer reads on a run. A surface asks here
//! which kind of work the step is, and says it in the reader's own language:
//! a line is a catalogue message per kind, with the record or item it acts in
//! as its argument ("Writing in Trip plan", "Schreibt in Trip plan"), so a
//! language whose word order differs reads its own sentence rather than words
//! assembled in English.
//!
//! The kind is the action's own declaration: what its app says it does
//! ([`StepKind`] on its action), else the part of the record the invocation
//! names ([`StepKind::of_anchor`]), else the declared operation of the change
//! itself ([`StepKind::of_edit`]). Nothing here reads an English verb out of a
//! label: an action whose declaration names no kind is [`StepKind::Work`],
//! which says the record it works in and never invents a verb.

use serde::{Deserialize, Serialize};

use crate::entry::{Did, EditOp};
use crate::interaction::{InteractionAnchor, SemanticInteraction};
use crate::key::CREATE_ACTION;

/// The kind of work a step does, as its action declares it.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum StepKind {
    /// It makes something new in the record.
    Create,
    /// It writes words into the record, at a place in it.
    Write,
    /// It changes what the record or one of its items says.
    Edit,
    /// It takes something away.
    Delete,
    /// It moves something elsewhere.
    Move,
    /// It only reads.
    Read,
    /// It runs something: a command, a program, a job.
    Run,
    /// Its declaration names no kind of work of its own.
    #[default]
    Work,
}

impl StepKind {
    /// The word a declaration names it by (`#[action(step = "create")]`).
    #[must_use]
    pub const fn word(self) -> &'static str {
        match self {
            Self::Create => "create",
            Self::Write => "write",
            Self::Edit => "edit",
            Self::Delete => "delete",
            Self::Move => "move",
            Self::Read => "read",
            Self::Run => "run",
            Self::Work => "work",
        }
    }

    /// What a step of this kind did, in the past tense, as a catalogue
    /// message: the word beside the characters a write left says what the
    /// person saw happen where the action declares no past-tense form of its
    /// own ([`ActionType::did`](crate::ActionType::did)).
    #[must_use]
    pub const fn did_message(self) -> &'static str {
        match self {
            Self::Create => DID_CREATED,
            Self::Write => DID_WROTE,
            Self::Edit => DID_EDITED,
            Self::Delete => DID_DELETED,
            Self::Move => DID_MOVED,
            Self::Read => DID_READ,
            Self::Run => DID_RAN,
            Self::Work => DID_WORKED,
        }
    }

    /// The kind `word` names.
    #[must_use]
    pub fn of_word(word: &str) -> Option<Self> {
        [
            Self::Create,
            Self::Write,
            Self::Edit,
            Self::Delete,
            Self::Move,
            Self::Read,
            Self::Run,
            Self::Work,
        ]
        .into_iter()
        .find(|kind| kind.word() == word)
    }

    /// The kind of step the change `op` is, as the change itself declares it:
    /// words written, an item added, something removed or moved.
    #[must_use]
    pub const fn of_edit(op: EditOp) -> Self {
        match op {
            EditOp::Splice | EditOp::Replace | EditOp::Mark => Self::Write,
            EditOp::Add
            | EditOp::Insert
            | EditOp::InsertRow
            | EditOp::InsertColumn
            | EditOp::React => Self::Create,
            EditOp::Remove
            | EditOp::RemoveRow
            | EditOp::RemoveColumn
            | EditOp::Unreact
            | EditOp::Forget => Self::Delete,
            EditOp::MoveTo => Self::Move,
            EditOp::Set | EditOp::SetCell => Self::Edit,
            EditOp::Settle => Self::Work,
        }
    }

    /// The kind of step an invocation is, from the part of the record it says
    /// it acts on: the characters of a text are words written into it, one of
    /// its items is that item changed, and the record as a whole names no kind
    /// of its own.
    #[must_use]
    pub const fn of_anchor(anchor: &InteractionAnchor) -> Option<Self> {
        match anchor {
            InteractionAnchor::Text { .. } | InteractionAnchor::Grid { .. } => Some(Self::Write),
            InteractionAnchor::ListItems { .. }
            | InteractionAnchor::Objects { .. }
            | InteractionAnchor::SemanticControl { .. } => Some(Self::Edit),
            // A timeline interval is a range of the record changed as a whole,
            // and a step on the record itself names no part to read a kind
            // from.
            InteractionAnchor::Timeline { .. } | InteractionAnchor::Resource => None,
        }
    }

    /// The kind of step a committed change is, from what it declares: a field
    /// edit's operation, a verb's own declaration ([`CREATE_ACTION`] makes
    /// something, a command parameter runs something), or a group naming what
    /// its members share. `None` for a step whose declaration names no kind of
    /// its own.
    #[must_use]
    pub fn of_did(what: &Did) -> Option<Self> {
        match what {
            Did::Edit(edit) => Some(Self::of_edit(edit.op)),
            Did::Verb(verb) => {
                if verb.action.action == CREATE_ACTION {
                    return Some(Self::Create);
                }
                // A parameter named for the command it runs: what the action
                // declared its input to be.
                verb.args
                    .keys()
                    .any(|name| COMMAND_PARAMS.contains(&name.as_str()))
                    .then_some(Self::Run)
            }
            Did::Group(group) => group.shared().and_then(Self::of_did),
            Did::History(_) => None,
        }
    }
}

/// The kind of step an invocation is: the kind its action declared, else the
/// part of the record it names ([`StepKind::of_anchor`]), else
/// [`StepKind::Work`].
#[must_use]
pub fn kind(declared: Option<StepKind>, anchor: &InteractionAnchor) -> StepKind {
    declared
        .or_else(|| StepKind::of_anchor(anchor))
        .unwrap_or(StepKind::Work)
}

/// One step, as every surface says it: which kind of work it is, and the one
/// name the line carries.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Step<'a> {
    pub kind: StepKind,
    /// The item's title where the step names one, else the record's name as
    /// its app shows it ("Trip plan").
    pub record: Option<&'a str>,
    /// The app the record belongs to, said where a step makes something new
    /// in it and no title names what yet ("Tasks").
    pub app: Option<&'a str>,
    /// What a run runs, as the caller passed it.
    pub command: Option<&'a str>,
    /// What a create makes: the kind of the record it makes it in, and the
    /// collection of that record it adds to as its declaration names it
    /// (`tasks.tracker`, `issues`). A surface says one of them by the
    /// collection's own noun ("an issue", "eine Aufgabe") where the app's
    /// catalogue holds one, and only says where the step works otherwise.
    pub makes: Option<(&'a str, &'a str)>,
}

impl<'a> Step<'a> {
    /// A step of `kind` on `record`.
    #[must_use]
    pub fn new(kind: StepKind, record: Option<&'a str>) -> Self {
        Self {
            kind,
            record: nonempty(record),
            app: None,
            command: None,
            makes: None,
        }
    }

    /// The same step, said in `app` where no record names it.
    #[must_use]
    pub fn in_app(mut self, app: Option<&'a str>) -> Self {
        self.app = nonempty(app);
        self
    }

    /// The same step, running `command`.
    #[must_use]
    pub fn running(mut self, command: Option<&'a str>) -> Self {
        self.command = nonempty(command);
        self
    }

    /// The same step, making something in the collection `field` of the record
    /// of `kind`: what a surface names by that collection's own noun.
    #[must_use]
    pub fn making(mut self, kind: &'a str, field: &'a str) -> Self {
        self.makes = Some((kind, field));
        self
    }

    /// The step `interaction` is: its action's declared kind, else the part of
    /// its record the invocation names, on the item's title or the record's
    /// name.
    #[must_use]
    pub fn of_interaction(interaction: &'a SemanticInteraction) -> Step<'a> {
        Self {
            kind: kind(interaction.action.step, &interaction.anchor),
            record: nonempty(Some(interaction.resource.label.as_str())),
            app: nonempty(
                interaction
                    .action
                    .app
                    .as_ref()
                    .map(|app| app.label.as_str()),
            ),
            command: None,
            makes: interaction
                .action
                .creates
                .as_deref()
                .and_then(|field| nonempty(Some(field)))
                .map(|field| (interaction.resource.kind.as_str(), field)),
        }
    }

    /// The catalogue message this step is said in, and its one argument: the
    /// name the line carries, and whether it is the record or what a run runs.
    /// A kind whose argument the step does not know says
    /// [`WORKING_ALONE`](self) instead of a sentence with a hole in it.
    #[must_use]
    pub fn message(&self) -> (&'static str, Option<(&'static str, &'a str)>) {
        fn named<'n>(
            key: &'static str,
            name: &'n str,
        ) -> (&'static str, Option<(&'static str, &'n str)>) {
            (key, Some(("record", name)))
        }
        match self.kind {
            StepKind::Create => match (self.record, self.app) {
                (Some(record), _) => named(CREATING, record),
                (None, Some(app)) => named(CREATING, app),
                (None, None) => (WORKING_ALONE, None),
            },
            StepKind::Write => self
                .record
                .map_or((WORKING_ALONE, None), |record| named(WRITING, record)),
            StepKind::Edit => self
                .record
                .map_or((WORKING_ALONE, None), |record| named(EDITING, record)),
            StepKind::Delete => self
                .record
                .map_or((WORKING_ALONE, None), |record| named(DELETING, record)),
            StepKind::Move => self
                .record
                .map_or((WORKING_ALONE, None), |record| named(MOVING, record)),
            StepKind::Read => self
                .record
                .map_or((WORKING_ALONE, None), |record| named(READING, record)),
            StepKind::Run => match (self.command, self.record) {
                (Some(command), _) => (RUNNING, Some(("command", command))),
                (None, Some(record)) => named(RUNNING_IN, record),
                (None, None) => (WORKING_ALONE, None),
            },
            StepKind::Work => self
                .record
                .map_or((WORKING_ALONE, None), |record| named(WORKING, record)),
        }
    }
}

/// The parameter names a verb declares for the command it runs: a verb
/// taking one is a step of [`StepKind::Run`], and the command is what a
/// person reads.
pub const COMMAND_PARAMS: &[&str] = &["command", "command_line", "cmd"];

/// A step that makes something new in the record or the app it names.
pub const CREATING: &str = "step-creating";
/// A step that makes one of a collection, named by that collection's noun.
pub const CREATING_ONE: &str = "step-creating-one";
/// A step that writes words into the record.
pub const WRITING: &str = "step-writing";
/// A step that changes what the record or one of its items says.
pub const EDITING: &str = "step-editing";
/// A step that takes something away.
pub const DELETING: &str = "step-deleting";
/// A step that moves something elsewhere.
pub const MOVING: &str = "step-moving";
/// A step that only reads.
pub const READING: &str = "step-reading";
/// A step that runs a command.
pub const RUNNING: &str = "step-running";
/// A step that runs something in the record it names.
pub const RUNNING_IN: &str = "step-running-in";
/// A step of work its declaration names no kind of.
pub const WORKING: &str = "step-working";
/// The same where the step names nothing at all.
pub const WORKING_ALONE: &str = "step-working-alone";

/// What a step of each kind did, in the past tense ([`StepKind::did_message`]).
pub const DID_CREATED: &str = "step-did-created";
pub const DID_WROTE: &str = "step-did-wrote";
pub const DID_EDITED: &str = "step-did-edited";
pub const DID_DELETED: &str = "step-did-deleted";
pub const DID_MOVED: &str = "step-did-moved";
pub const DID_READ: &str = "step-did-read";
pub const DID_RAN: &str = "step-did-ran";
pub const DID_WORKED: &str = "step-did-worked";

/// `name` trimmed, unless that leaves nothing to say.
fn nonempty(name: Option<&str>) -> Option<&str> {
    name.map(str::trim).filter(|name| !name.is_empty())
}

#[cfg(test)]
mod tests {
    #![allow(
        clippy::unwrap_used,
        clippy::expect_used,
        reason = "in a test the unwrap is the assertion"
    )]

    use super::*;
    use crate::interaction::{InteractionAction, InteractionTextRange};
    use crate::{ActionApp, ActionResource, InteractionPhase, InvocationId};

    fn interaction(
        step: Option<StepKind>,
        anchor: InteractionAnchor,
        record: &str,
    ) -> SemanticInteraction {
        SemanticInteraction {
            version: crate::INTERACTION_VERSION,
            invocation: InvocationId(uuid::Uuid::from_u128(1)),
            sequence: 1,
            actor: crate::Acting::agent("quill", "ada"),
            phase: InteractionPhase::Applying,
            action: InteractionAction {
                id: "create".into(),
                label: "Create an issue".into(),
                app: Some(ActionApp {
                    id: "so.tilo.tasks".into(),
                    label: "Tasks".into(),
                }),
                step,
                creates: None,
                did: None,
            },
            resource: ActionResource {
                id: "tasks.tracker".into(),
                kind: "tasks.tracker".into(),
                label: record.into(),
            },
            anchor,
            group: None,
        }
    }

    tilo_test_env::scenario! {
        fn a_step_names_its_kind_and_record;

        phase a_steps_kind_is_declared_else_read_from_the_part_it_acts_on;
        // A step's kind is its action's own declaration where it names one, and
        // the part of the record it acts on where it does not.
        {
            let text = InteractionAnchor::Text {
                region: "text".into(),
                ranges: vec![InteractionTextRange {
                    block: "note".into(),
                    start: 0,
                    end: 0,
                }],
            };
            let created = interaction(Some(StepKind::Create), InteractionAnchor::Resource, "Tasks");
            assert_eq!(Step::of_interaction(&created).kind, StepKind::Create);
            let written = interaction(None, text, "Trip plan");
            let writing = Step::of_interaction(&written);
            assert_eq!(writing.kind, StepKind::Write);
            assert_eq!(writing.message(), (WRITING, Some(("record", "Trip plan"))));
            let items = InteractionAnchor::ListItems {
                ids: vec!["issue-1".into()],
            };
            assert_eq!(
                Step::of_interaction(&interaction(None, items, "Book the ferry")).kind,
                StepKind::Edit,
                "an item's own step changes that item"
            );
            assert_eq!(
                Step::of_interaction(&interaction(None, InteractionAnchor::Resource, "Issues")).kind,
                StepKind::Work
            );
        }

        phase a_step_names_its_record_or_says_only_what_it_is;
        // A declared kind says the record, and the app where nothing is named
        // yet; a kind with no name says only what it is.
        {
            let made = interaction(
                Some(StepKind::Create),
                InteractionAnchor::Resource,
                "Issues",
            );
            let created = Step::of_interaction(&made).in_app(Some(" Tasks "));
            assert_eq!(created.message(), (CREATING, Some(("record", "Issues"))));
            // A create whose declaration names the collection it adds to says what
            // it makes: the record's kind and that collection.
            let mut declaring = made.clone();
            declaring.action.creates = Some(" issues ".into());
            assert_eq!(
                Step::of_interaction(&declaring).makes,
                Some(("tasks.tracker", "issues")),
                "what it makes, named by the record's kind and its collection"
            );
            assert_eq!(created.makes, None, "a create that names none makes none");
            assert_eq!(
                Step::new(StepKind::Create, None)
                    .in_app(Some("Tasks"))
                    .message(),
                (CREATING, Some(("record", "Tasks")))
            );
            assert_eq!(
                Step::new(StepKind::Delete, None).message(),
                (WORKING_ALONE, None)
            );
            assert_eq!(
                Step::new(StepKind::Run, Some("Terminal")).running(Some("cargo build")),
                Step {
                    kind: StepKind::Run,
                    record: Some("Terminal"),
                    app: None,
                    command: Some("cargo build"),
                    makes: None,
                }
            );
            assert_eq!(
                Step::new(StepKind::Run, Some("Terminal")).message(),
                (RUNNING_IN, Some(("record", "Terminal")))
            );
        }

        phase a_committed_change_names_its_kind_as_it_declared_it;
        // A committed change names its kind by what it declared: the operation of
        // a field edit, the platform's make, the command a verb runs.
        {
            for (op, kind) in [
                (EditOp::Splice, StepKind::Write),
                (EditOp::Replace, StepKind::Write),
                (EditOp::Insert, StepKind::Create),
                (EditOp::Remove, StepKind::Delete),
                (EditOp::MoveTo, StepKind::Move),
                (EditOp::Set, StepKind::Edit),
            ] {
                assert_eq!(StepKind::of_edit(op), kind, "{op:?}");
            }
            let made = Did::verb(
                crate::ActionKey::new("so.tilo.notes", "notes.note", CREATE_ACTION),
                std::iter::empty::<(String, crate::Scalar)>(),
            );
            assert_eq!(StepKind::of_did(&made), Some(StepKind::Create));
            let command = Did::verb(
                crate::ActionKey::new("so.tilo.terminal", "terminal.session", "run"),
                [(
                    "command".to_owned(),
                    crate::Scalar::from_json(&serde_json::json!("cargo build")).unwrap(),
                )],
            );
            assert_eq!(StepKind::of_did(&command), Some(StepKind::Run));
            let renamed = Did::verb(
                crate::ActionKey::new("so.tilo.notes", "notes.note", "rename"),
                std::iter::empty::<(String, crate::Scalar)>(),
            );
            assert_eq!(StepKind::of_did(&renamed), None);
        }

        phase a_kind_reads_back_from_its_word;
        {
            for kind in [
                StepKind::Create,
                StepKind::Write,
                StepKind::Edit,
                StepKind::Delete,
                StepKind::Move,
                StepKind::Read,
                StepKind::Run,
                StepKind::Work,
            ] {
                assert_eq!(StepKind::of_word(kind.word()), Some(kind));
            }
            assert_eq!(StepKind::of_word("writing"), None);
        }
    }
}