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
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
//! Semantic, transient presence for an action invocation.
//!
//! An agent does not have a mouse pointer to mirror.  This vocabulary names
//! the resource it is working on and the application-native selection that
//! resource understands.  Receivers resolve those stable anchors against
//! their own layout; pixels, viewport positions, and widget indices never
//! cross the wire.

use serde::{Deserialize, Serialize};

use crate::{ActionApp, ActionResource, InvocationId, WorkGroup};
use tilo_action_policy::Acting;

/// Wire version understood by this crate.
pub const INTERACTION_VERSION: u16 = 2;
/// Hard ceiling for one JSON-encoded update at a trust boundary.
pub const MAX_INTERACTION_BYTES: usize = 32 * 1024;
pub const MAX_ANCHOR_ITEMS: usize = 64;
pub const MAX_ID_BYTES: usize = 512;
pub const MAX_LABEL_BYTES: usize = 512;
pub const MAX_DETAIL_BYTES: usize = 2 * 1024;

/// A stable character range within a document block.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct InteractionTextRange {
    pub block: String,
    pub start: u64,
    pub end: u64,
}

/// A stable inclusive cell rectangle. `sheet` lives on the enclosing anchor
/// so a multi-range selection cannot accidentally span workbooks/sheets.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct InteractionGridRange {
    pub start_col: u32,
    pub start_row: u32,
    pub end_col: u32,
    pub end_row: u32,
}

/// Application-native target of an interaction.  Every variant is semantic:
/// receivers turn it into their current geometry and may fall back to the
/// enclosing resource when an anchor is off-screen or no longer exists.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(remote = "Self", tag = "kind", rename_all = "snake_case")]
pub enum InteractionAnchor {
    /// The whole resource is the narrowest truthful target available.
    Resource,
    /// A durable node in the app's semantic/accessibility tree.
    SemanticControl { id: String },
    /// One or more ranges in stable document blocks.
    Text {
        region: String,
        ranges: Vec<InteractionTextRange>,
    },
    /// One or more cell rectangles in a stable sheet identity.
    Grid {
        sheet: String,
        ranges: Vec<InteractionGridRange>,
    },
    /// Stable object ids, e.g. shapes, slides, clips, or document blocks.
    Objects { ids: Vec<String> },
    /// Stable rows/items, e.g. filesystem resource addresses.
    ListItems { ids: Vec<String> },
    /// A semantic media interval; times are content time, never screen space.
    Timeline {
        track: Option<String>,
        start_ms: u64,
        end_ms: u64,
    },
}

read_through_json_value!(InteractionAnchor);

/// What the invocation is visibly doing.  Terminal details complement the
/// durable invocation result; they do not replace it.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(remote = "Self", tag = "phase", rename_all = "snake_case")]
pub enum InteractionPhase {
    Locating,
    Applying,
    Progress {
        label: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        completed: Option<u64>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        total: Option<u64>,
    },
    Waiting {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        reason: Option<String>,
    },
    Committed,
    Failed {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        code: Option<String>,
        message: String,
    },
    Cancelled {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        message: Option<String>,
    },
}

read_through_json_value!(InteractionPhase);

impl InteractionPhase {
    pub fn is_terminal(&self) -> bool {
        matches!(
            self,
            Self::Committed | Self::Failed { .. } | Self::Cancelled { .. }
        )
    }
}

/// Action identity and human label from the application's current catalogue.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct InteractionAction {
    pub id: String,
    pub label: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub app: Option<ActionApp>,
    /// The kind of step the action declares it takes
    /// ([`StepKind`](crate::StepKind)), so a surface says it in the reader's
    /// language instead of reading it off the label's English words. Absent
    /// for an action whose declaration names none, whose step reads as the
    /// part of the record it acts on.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub step: Option<crate::StepKind>,
    /// The collection of its resource the action adds to, when it declares one
    /// (`writes = issues`): what a create makes, named by that collection's
    /// own noun in the reader's language
    /// ([`ActionContract::creates`](crate::ActionContract::creates)).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub creates: Option<String>,
    /// What the action did, in the app's own words, said after who did it
    /// ("renamed", "replaced"): the past-tense form its app declares
    /// ([`ActionType::did`](crate::ActionType::did)), so a surface says what
    /// happened where the action's menu label only names the place it acts
    /// on. Absent where the app declares none; a surface then says the kind
    /// of step that was taken.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub did: Option<String>,
}

/// One broker-normalized, transient semantic interaction event.
///
/// `sequence` is monotonic within an invocation. The broker owns the actor,
/// sequence and legal lifecycle transitions; an application contributes only
/// the target it can resolve from the freshly encoded action and live model.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SemanticInteraction {
    pub version: u16,
    pub invocation: InvocationId,
    pub sequence: u64,
    pub actor: Acting,
    pub phase: InteractionPhase,
    pub action: InteractionAction,
    pub resource: ActionResource,
    pub anchor: InteractionAnchor,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub group: Option<WorkGroup>,
}

/// Transport/UI spelling for a semantic interaction lifecycle update.
///
/// The alias keeps the data model's descriptive name while letting stream and
/// event APIs use `InteractionUpdate` alongside `InvocationUpdate`.
pub type InteractionUpdate = SemanticInteraction;

impl SemanticInteraction {
    /// The characters it writes into the text `text` of block `block` (in `region`, when one is
    /// named), as byte offsets in it: the `Text` range its anchor names there, counted in
    /// characters because a place counts them that way.
    #[must_use]
    pub fn written_in(
        &self,
        region: Option<&str>,
        block: &str,
        text: &str,
    ) -> Option<(usize, usize)> {
        let InteractionAnchor::Text {
            region: written,
            ranges,
        } = &self.anchor
        else {
            return None;
        };
        if region.is_some_and(|region| region != written) {
            return None;
        }
        // A caller may name a block by the start of its id, as the document resolves it: a write that
        // landed named one block only.
        let range = ranges.iter().find(|range| {
            range.block == block || (!range.block.is_empty() && block.starts_with(&range.block))
        })?;
        let chars = text.chars().count();
        let start = usize::try_from(range.start).ok()?.min(chars);
        let end = usize::try_from(range.end).ok()?.min(chars).max(start);
        let byte = |index: usize| {
            text.char_indices()
                .nth(index)
                .map_or(text.len(), |(byte, _)| byte)
        };
        Some((byte(start), byte(end)))
    }

    /// Replace attribution with the identity authenticated by the broker.
    ///
    /// `actor` in decoded application/agent input is an untrusted claim. A
    /// broker must call this (and assign its own monotonic `sequence`) before
    /// validating or broadcasting the normalized event. Presence consumers
    /// may trust attribution only on broker-originated streams.
    #[must_use]
    pub fn normalized_by_broker(mut self, actor: Acting, sequence: u64) -> Self {
        self.actor = actor;
        self.sequence = sequence;
        self
    }

    /// Validate size and semantic bounds before accepting an untrusted update.
    /// Unknown additive object fields remain serde-compatible; a semantic
    /// change uses a new `version` and is rejected here by older readers.
    pub fn validate(&self) -> Result<(), InteractionViolation> {
        if self.version != INTERACTION_VERSION {
            return Err(issue("version", "unsupported interaction version"));
        }
        for node in self.actor.nodes() {
            validate_id("actor", node.by.id())?;
        }
        validate_id("action.id", &self.action.id)?;
        validate_label("action.label", &self.action.label)?;
        if let Some(did) = &self.action.did {
            validate_label("action.did", did)?;
        }
        validate_resource(&self.resource)?;
        if let Some(app) = &self.action.app {
            validate_id("action.app.id", &app.id)?;
            validate_label("action.app.label", &app.label)?;
        }
        if let Some(group) = &self.group {
            validate_id("group.id", &group.id)?;
            if let Some(label) = &group.label {
                validate_label("group.label", label)?;
            }
            validate_id("group.kind", &group.kind)?;
        }
        validate_phase(&self.phase)?;
        validate_anchor(&self.anchor)?;
        let encoded = serde_json::to_vec(self)
            .map_err(|_| issue("interaction", "interaction could not be encoded"))?;
        if encoded.len() > MAX_INTERACTION_BYTES {
            return Err(issue("interaction", "encoded interaction is too large"));
        }
        Ok(())
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct InteractionViolation {
    pub field: &'static str,
    pub reason: &'static str,
}

impl std::fmt::Display for InteractionViolation {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(formatter, "{}: {}", self.field, self.reason)
    }
}

impl std::error::Error for InteractionViolation {}

const fn issue(field: &'static str, reason: &'static str) -> InteractionViolation {
    InteractionViolation { field, reason }
}

fn validate_nonempty(
    field: &'static str,
    value: &str,
    maximum: usize,
) -> Result<(), InteractionViolation> {
    if value.trim().is_empty() {
        return Err(issue(field, "must not be empty"));
    }
    if value.len() > maximum {
        return Err(issue(field, "is too long"));
    }
    Ok(())
}

fn validate_id(field: &'static str, value: &str) -> Result<(), InteractionViolation> {
    validate_nonempty(field, value, MAX_ID_BYTES)
}

fn validate_label(field: &'static str, value: &str) -> Result<(), InteractionViolation> {
    validate_nonempty(field, value, MAX_LABEL_BYTES)
}

fn validate_resource(resource: &ActionResource) -> Result<(), InteractionViolation> {
    validate_id("resource.id", &resource.id)?;
    validate_id("resource.kind", &resource.kind)?;
    validate_label("resource.label", &resource.label)
}

fn validate_detail(field: &'static str, value: &str) -> Result<(), InteractionViolation> {
    if value.len() > MAX_DETAIL_BYTES {
        return Err(issue(field, "is too long"));
    }
    Ok(())
}

fn validate_phase(phase: &InteractionPhase) -> Result<(), InteractionViolation> {
    match phase {
        InteractionPhase::Waiting {
            reason: Some(reason),
        } => validate_detail("phase.reason", reason),
        InteractionPhase::Progress {
            label,
            completed,
            total,
        } => {
            validate_nonempty("phase.label", label, MAX_LABEL_BYTES)?;
            if let (Some(completed), Some(total)) = (completed, total)
                && completed > total
            {
                return Err(issue("phase.progress", "completed exceeds total"));
            }
            Ok(())
        }
        InteractionPhase::Failed { code, message } => {
            if let Some(code) = code {
                validate_id("phase.code", code)?;
            }
            validate_nonempty("phase.message", message, MAX_DETAIL_BYTES)
        }
        InteractionPhase::Cancelled {
            message: Some(message),
        } => validate_detail("phase.message", message),
        InteractionPhase::Locating
        | InteractionPhase::Applying
        | InteractionPhase::Waiting { reason: None }
        | InteractionPhase::Committed
        | InteractionPhase::Cancelled { message: None } => Ok(()),
    }
}

fn validate_anchor(anchor: &InteractionAnchor) -> Result<(), InteractionViolation> {
    match anchor {
        InteractionAnchor::Resource => Ok(()),
        InteractionAnchor::SemanticControl { id } => validate_id("anchor.id", id),
        InteractionAnchor::Text { region, ranges } => {
            validate_id("anchor.region", region)?;
            validate_count("anchor.ranges", ranges.len())?;
            for range in ranges {
                validate_id("anchor.range.block", &range.block)?;
                if range.end < range.start {
                    return Err(issue("anchor.range", "range end precedes start"));
                }
            }
            Ok(())
        }
        InteractionAnchor::Grid { sheet, ranges } => {
            validate_id("anchor.sheet", sheet)?;
            validate_count("anchor.ranges", ranges.len())?;
            if ranges
                .iter()
                .any(|range| range.end_col < range.start_col || range.end_row < range.start_row)
            {
                return Err(issue("anchor.range", "range end precedes start"));
            }
            Ok(())
        }
        InteractionAnchor::Objects { ids } | InteractionAnchor::ListItems { ids } => {
            validate_count("anchor.ids", ids.len())?;
            for id in ids {
                validate_id("anchor.id", id)?;
            }
            Ok(())
        }
        InteractionAnchor::Timeline {
            track,
            start_ms,
            end_ms,
        } => {
            if let Some(track) = track {
                validate_id("anchor.track", track)?;
            }
            if end_ms < start_ms {
                return Err(issue("anchor.range", "range end precedes start"));
            }
            Ok(())
        }
    }
}

fn validate_count(field: &'static str, count: usize) -> Result<(), InteractionViolation> {
    if count == 0 {
        return Err(issue(field, "must not be empty"));
    }
    if count > MAX_ANCHOR_ITEMS {
        return Err(issue(field, "has too many items"));
    }
    Ok(())
}

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

    fn example(anchor: InteractionAnchor) -> SemanticInteraction {
        SemanticInteraction {
            version: INTERACTION_VERSION,
            invocation: InvocationId::new(),
            sequence: 2,
            actor: Acting::agent("scribe", "ada"),
            phase: InteractionPhase::Applying,
            action: InteractionAction {
                id: "format-range".into(),
                label: "Format range".into(),
                app: Some(ActionApp {
                    id: "org.tilo.Sheets".into(),
                    label: "Sheets".into(),
                }),
                step: None,
                creates: None,
                did: None,
            },
            resource: ActionResource {
                id: "sheets.sheet:budget".into(),
                kind: "sheets.sheet".into(),
                label: "Budget".into(),
            },
            anchor,
            group: Some(WorkGroup {
                id: "task:42".into(),
                label: Some("Prepare budget".into()),
                kind: "task".into(),
                declared_id: None,
                session: None,
            }),
        }
    }

    /// Versioned grid interactions round-trip, additive fields are ignored but unknown versions are
    /// refused, and the broker replaces claimed attribution and sequence.
    /// Runs each phase below in order; every phase builds its own fixture.
    #[test]
    fn the_interaction_wire_is_versioned_and_broker_normalised() {
        versioned_grid_interaction_round_trips();
        additive_fields_are_ignored_but_unknown_versions_are_refused();
        broker_normalization_replaces_claimed_attribution_and_sequence();
    }

    fn versioned_grid_interaction_round_trips() {
        let interaction = example(InteractionAnchor::Grid {
            sheet: "sheet:budget".into(),
            ranges: vec![InteractionGridRange {
                start_col: 1,
                start_row: 2,
                end_col: 4,
                end_row: 8,
            }],
        });
        interaction.validate().expect("valid interaction");
        let json = serde_json::to_string(&interaction).expect("encode");
        let decoded: SemanticInteraction = serde_json::from_str(&json).expect("decode");
        assert_eq!(decoded, interaction);
        assert!(!json.contains("pixel"));
        assert!(!json.contains("x\""));
    }

    fn additive_fields_are_ignored_but_unknown_versions_are_refused() {
        let interaction = example(InteractionAnchor::Resource);
        let mut value = serde_json::to_value(&interaction).expect("encode");
        value
            .as_object_mut()
            .expect("object")
            .insert("future_hint".into(), serde_json::json!(true));
        let decoded: SemanticInteraction = serde_json::from_value(value).expect("decode");
        assert_eq!(decoded, interaction);

        let mut future = interaction;
        future.version = INTERACTION_VERSION + 1;
        assert_eq!(future.validate().unwrap_err().field, "version");
    }

    fn broker_normalization_replaces_claimed_attribution_and_sequence() {
        let claimed = example(InteractionAnchor::Resource);
        let normalized = claimed.normalized_by_broker(Acting::agent("reviewer", "ada"), 17);
        assert_eq!(normalized.actor, Acting::agent("reviewer", "ada"));
        assert_eq!(normalized.sequence, 17);
    }

    /// Anchors are non-empty, ordered and bounded; labels and terminal details are bounded; terminal
    /// phases are explicit; progress is labelled and in range.
    /// Runs each phase below in order; every phase builds its own fixture.
    #[test]
    fn interaction_fields_are_explicit_and_bounded() {
        anchors_are_nonempty_ordered_and_bounded();
        labels_and_terminal_details_are_bounded();
        terminal_phases_are_explicit();
        progress_is_labelled_and_in_range();
    }

    fn anchors_are_nonempty_ordered_and_bounded() {
        let backwards = example(InteractionAnchor::Text {
            region: "body".into(),
            ranges: vec![InteractionTextRange {
                block: "block:1".into(),
                start: 9,
                end: 3,
            }],
        });
        assert_eq!(backwards.validate().unwrap_err().field, "anchor.range");

        let too_many = example(InteractionAnchor::Objects {
            ids: (0..=MAX_ANCHOR_ITEMS)
                .map(|n| format!("shape:{n}"))
                .collect(),
        });
        assert_eq!(too_many.validate().unwrap_err().field, "anchor.ids");

        let empty = example(InteractionAnchor::ListItems { ids: Vec::new() });
        assert_eq!(empty.validate().unwrap_err().field, "anchor.ids");
    }

    fn labels_and_terminal_details_are_bounded() {
        let mut oversized = example(InteractionAnchor::Resource);
        oversized.phase = InteractionPhase::Failed {
            code: Some("action_failed".into()),
            message: "x".repeat(MAX_DETAIL_BYTES + 1),
        };
        assert_eq!(oversized.validate().unwrap_err().field, "phase.message");

        oversized.phase = InteractionPhase::Committed;
        oversized.resource.label = "x".repeat(MAX_LABEL_BYTES + 1);
        assert_eq!(oversized.validate().unwrap_err().field, "resource.label");

        oversized.resource.label = "Label".into();
        oversized.action.did = Some("x".repeat(MAX_LABEL_BYTES + 1));
        assert_eq!(oversized.validate().unwrap_err().field, "action.did");
    }

    fn terminal_phases_are_explicit() {
        assert!(!InteractionPhase::Locating.is_terminal());
        assert!(!InteractionPhase::Applying.is_terminal());
        assert!(
            !InteractionPhase::Progress {
                label: "Uploading".into(),
                completed: Some(3),
                total: Some(10),
            }
            .is_terminal()
        );
        assert!(InteractionPhase::Committed.is_terminal());
        assert!(
            InteractionPhase::Failed {
                code: None,
                message: "no".into()
            }
            .is_terminal()
        );
        assert!(InteractionPhase::Cancelled { message: None }.is_terminal());
    }

    fn progress_is_labelled_and_in_range() {
        let mut interaction = example(InteractionAnchor::Resource);
        interaction.phase = InteractionPhase::Progress {
            label: String::new(),
            completed: None,
            total: None,
        };
        assert_eq!(interaction.validate().unwrap_err().field, "phase.label");

        interaction.phase = InteractionPhase::Progress {
            label: "Indexing".into(),
            completed: Some(11),
            total: Some(10),
        };
        assert_eq!(interaction.validate().unwrap_err().field, "phase.progress");
    }
}