Skip to main content

smix_authoring_ir/
lib.rs

1#![doc = include_str!("../README.md")]
2#![deny(missing_docs)]
3#![deny(rustdoc::broken_intra_doc_links)]
4
5//! smix-authoring-ir — IRAction (intermediate representation) +
6//! RecorderError + sort helper (stone, cold path).
7//!
8//! Each [`IRAction`] is one user-visible side-effecting step in a
9//! recorded session; the IR feeds the generator-smix-ts +
10//! generator-maestro-yaml dual output.
11//!
12//! Scope note: IR is captured from the **smix API channel** (host-side
13//! instrumentation in `RecordSession`), not from a sim-side AX
14//! notification swizzle. The swizzle path cannot surface user-tap events
15//! originating outside the smix API channel. "User taps sim screen
16//! manually with smix watching" is a separate architecture.
17
18#![doc(html_root_url = "https://docs.smix.dev/smix-authoring-ir")]
19
20use serde::{Deserialize, Serialize};
21use smix_input::{KeyName, SwipeDirection};
22use smix_selector::Selector;
23use std::fmt;
24
25/// One user-visible side-effecting step in a recorded session.
26///
27/// Wire serializes as an internally-tagged enum keyed by `kind`: serde
28/// `tag = "kind", rename_all = "camelCase"` emits
29/// `{ kind: 'tap', selector: ..., timestampMs: ... }`.
30#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
31#[serde(tag = "kind", rename_all = "camelCase")]
32pub enum IRAction {
33    /// Tap an element matched by `selector`.
34    Tap {
35        /// Selector picking the tap target.
36        selector: Selector,
37        /// Capture-time timestamp in milliseconds.
38        #[serde(rename = "timestampMs")]
39        timestamp_ms: f64,
40    },
41    /// Tap an element and type `text` into it.
42    Fill {
43        /// Selector picking the input field.
44        selector: Selector,
45        /// Text to type after the tap.
46        text: String,
47        /// Capture-time timestamp in milliseconds.
48        #[serde(rename = "timestampMs")]
49        timestamp_ms: f64,
50    },
51    /// Tap an element and clear its value.
52    Clear {
53        /// Selector picking the input to clear.
54        selector: Selector,
55        /// Capture-time timestamp in milliseconds.
56        #[serde(rename = "timestampMs")]
57        timestamp_ms: f64,
58    },
59    /// Press a single keyboard key.
60    PressKey {
61        /// Key name (`Return` / `Tab` / arrows / etc.).
62        key: KeyName,
63        /// Capture-time timestamp in milliseconds.
64        #[serde(rename = "timestampMs")]
65        timestamp_ms: f64,
66    },
67    /// Swipe in a direction, optionally anchored to an element.
68    Swipe {
69        /// Swipe direction.
70        direction: SwipeDirection,
71        /// Optional anchor element (swipe starts from its centroid).
72        #[serde(default, skip_serializing_if = "Option::is_none")]
73        from: Option<Selector>,
74        /// Capture-time timestamp in milliseconds.
75        #[serde(rename = "timestampMs")]
76        timestamp_ms: f64,
77    },
78    /// Navigate back (system back gesture / button).
79    GoBack {
80        /// Capture-time timestamp in milliseconds.
81        #[serde(rename = "timestampMs")]
82        timestamp_ms: f64,
83    },
84    /// Block playback until an element becomes visible.
85    WaitFor {
86        /// Selector to wait for.
87        selector: Selector,
88        /// Capture-time timestamp in milliseconds.
89        #[serde(rename = "timestampMs")]
90        timestamp_ms: f64,
91    },
92    /// Dismiss the on-screen keyboard.
93    HideKeyboard {
94        /// Capture-time timestamp in milliseconds.
95        #[serde(rename = "timestampMs")]
96        timestamp_ms: f64,
97    },
98}
99
100impl IRAction {
101    /// Timestamp in milliseconds (Unix epoch or session-relative, depending
102    /// on capture site). Stable accessor across variants.
103    #[must_use]
104    pub fn timestamp_ms(&self) -> f64 {
105        match self {
106            IRAction::Tap { timestamp_ms, .. }
107            | IRAction::Fill { timestamp_ms, .. }
108            | IRAction::Clear { timestamp_ms, .. }
109            | IRAction::PressKey { timestamp_ms, .. }
110            | IRAction::Swipe { timestamp_ms, .. }
111            | IRAction::GoBack { timestamp_ms }
112            | IRAction::WaitFor { timestamp_ms, .. }
113            | IRAction::HideKeyboard { timestamp_ms } => *timestamp_ms,
114        }
115    }
116
117    /// Wire `kind` string for log / generator / debug rendering. Mirrors
118    /// the camelCase serde tag.
119    #[must_use]
120    pub fn kind(&self) -> &'static str {
121        match self {
122            IRAction::Tap { .. } => "tap",
123            IRAction::Fill { .. } => "fill",
124            IRAction::Clear { .. } => "clear",
125            IRAction::PressKey { .. } => "pressKey",
126            IRAction::Swipe { .. } => "swipe",
127            IRAction::GoBack { .. } => "goBack",
128            IRAction::WaitFor { .. } => "waitFor",
129            IRAction::HideKeyboard { .. } => "hideKeyboard",
130        }
131    }
132}
133
134// -------------------- RecorderError --------------------------------------
135
136/// Reasons a recorder session might fail. The `cleanup-*` variants
137/// surface claude-CLI AI-cleanup failures distinctly from failures of
138/// the recording itself.
139#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
140#[serde(rename_all = "kebab-case")]
141pub enum RecorderErrorReason {
142    /// Session had zero actions when generation was requested.
143    EmptySession,
144    /// One action in the session was structurally invalid.
145    MalformedAction,
146    /// Claude CLI cleanup subprocess exited non-zero.
147    CleanupFailed,
148    /// Claude CLI cleanup returned an empty body.
149    CleanupEmptyOutput,
150    /// Claude CLI cleanup returned a body that failed validation.
151    CleanupInvalidOutput,
152}
153
154impl RecorderErrorReason {
155    /// kebab-case wire string.
156    #[must_use]
157    pub fn as_str(self) -> &'static str {
158        match self {
159            RecorderErrorReason::EmptySession => "empty-session",
160            RecorderErrorReason::MalformedAction => "malformed-action",
161            RecorderErrorReason::CleanupFailed => "cleanup-failed",
162            RecorderErrorReason::CleanupEmptyOutput => "cleanup-empty-output",
163            RecorderErrorReason::CleanupInvalidOutput => "cleanup-invalid-output",
164        }
165    }
166}
167
168impl fmt::Display for RecorderErrorReason {
169    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
170        f.write_str(self.as_str())
171    }
172}
173
174/// Recorder-side failure, distinct from SDK-side ExpectationFailure.
175/// CLI / SDK consumers may surface this directly or wrap with context.
176#[derive(Clone, Debug)]
177pub struct RecorderError {
178    /// Failure-reason discriminator.
179    pub reason: RecorderErrorReason,
180    /// Free-form human-readable detail.
181    pub message: String,
182}
183
184impl RecorderError {
185    /// Construct a [`RecorderError`] with reason + message.
186    #[must_use]
187    pub fn new<S: Into<String>>(reason: RecorderErrorReason, message: S) -> Self {
188        RecorderError {
189            reason,
190            message: message.into(),
191        }
192    }
193}
194
195impl fmt::Display for RecorderError {
196    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
197        write!(f, "RecorderError[{}]: {}", self.reason, self.message)
198    }
199}
200
201impl std::error::Error for RecorderError {}
202
203// -------------------- sort helper ----------------------------------------
204
205/// Sort actions by timestamp ascending. Idempotent. Used when multiple
206/// recorders feed the same session (e.g. parallel cells, future feature)
207/// to merge chronologically. Mirrors TS `sortByTimestamp` 1:1.
208#[must_use]
209pub fn sort_by_timestamp(actions: &[IRAction]) -> Vec<IRAction> {
210    let mut out = actions.to_vec();
211    out.sort_by(|a, b| {
212        a.timestamp_ms()
213            .partial_cmp(&b.timestamp_ms())
214            .unwrap_or(std::cmp::Ordering::Equal)
215    });
216    out
217}