qontinui-types 0.2.0

Canonical DTO types for Qontinui. Rust is the source of truth; TypeScript and Python are generated from JSON Schema emitted by schemars.
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
//! IR (Intermediate Representation) + Legacy wire types for the Spec API.
//!
//! This module is the **single source of truth** for IR types shared across
//! the Qontinui stack. The runner (`qontinui-runner/src-tauri`), supervisor
//! (`qontinui-supervisor`), and any future matcher/projection crates all
//! consume these types via `qontinui_types::ir::*`.
//!
//! ## Two type families
//!
//! - **IR types** (`Ir*`) — authoring surface. The `state-machine.derived.json`
//!   files on disk match this shape (camelCase wire format). Hand-edited or
//!   plugin-generated; never auto-derived from the projection.
//! - **Legacy types** (`Legacy*`) — runtime/output surface. The
//!   `spec.uibridge.json` files match this shape. Auto-regenerated by the
//!   projection layer (`spec_api::projection`) every time the IR is rewritten.
//!
//! ## Conventions
//!
//! - Wire format is `camelCase` via `#[serde(rename_all = "camelCase")]`.
//! - Field-renaming exceptions use explicit `#[serde(rename = "...")]` (the
//!   `IrCrossRef::r#ref` field uses the Rust raw-identifier `r#ref` so the
//!   field name can match the reserved word `ref` on the wire).
//! - Types containing `f64` (e.g. `IrState::path_cost`) cannot derive `Eq`;
//!   the `Eq` vs `PartialEq` choice on each struct is deliberate.
//! - Free-form payload fields (like `IrTransitionAction::params`,
//!   `IrAssertionTarget::criteria`) are `serde_json::Value` so synthesis can
//!   emit partially-populated criteria without tripping the schema and so the
//!   projection passes the bytes through verbatim.

use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;

// ---------------------------------------------------------------------------
// Element criteria
// ---------------------------------------------------------------------------

/// Mirror of `IRElementCriteria`
/// (`qontinui-schemas/ts/src/ui-bridge-ir/element-criteria.ts`).
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct IrElementCriteria {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub role: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tag_name: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub text: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub text_contains: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub aria_label: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub accessible_name: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
    /// HTML attributes to check (exact string match). Stored as a `BTreeMap`
    /// so JSON serialization is deterministic (matters for byte-stable
    /// projection output).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub attributes: Option<BTreeMap<String, String>>,
}

// ---------------------------------------------------------------------------
// Primitives — IR-only fields (provenance, metadata, effect, cross-refs)
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct IrProvenance {
    /// "hand-authored" | "build-plugin" | "ai-generated" | "migrated"
    pub source: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub file: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub line: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub column: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub plugin_version: Option<String>,
    /// Lifecycle status for the flywheel coverage-growth loop. `None` =
    /// implicitly `Promoted` (legacy + on-disk specs that predate the field).
    /// Set to `Proposed` by `spec_authoring`, `Pending` when staged in
    /// `_pending/`, `Promoted` after the 2-green sweep moves the file to
    /// `pages/<id>/`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub status: Option<ProposalStatus>,
}

/// Lifecycle status for spec proposals produced by the Stream E coverage-growth
/// flywheel. `None` on an existing `IrProvenance` means the spec predates the
/// flywheel and is implicitly `Promoted`.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "kebab-case")]
pub enum ProposalStatus {
    /// Candidate emitted by `spec_authoring` but not yet validated.
    Proposed,
    /// Candidate landed in `_pending/`; awaiting consecutive greens.
    Pending,
    /// Candidate has been promoted to `pages/<id>/`. Default for legacy specs.
    Promoted,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct IrMetadata {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub purpose: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tags: Option<Vec<String>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub related_elements: Option<Vec<String>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub notes: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct IrCrossRef {
    pub doc: String,
    /// `ref` is reserved in Rust — serialize as `ref` for the wire while
    /// using `r#ref` as the Rust field name.
    #[serde(rename = "ref")]
    pub r#ref: String,
}

// ---------------------------------------------------------------------------
// Wait spec / transition action
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct IrWaitSpec {
    /// "idle" | "element" | "state" | "time" | "condition" | "vanish" | "change" | "stable"
    #[serde(rename = "type")]
    pub kind: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub query: Option<IrElementCriteria>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub state_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ms: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub timeout: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub property: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub quiet_period_ms: Option<u64>,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct IrTransitionAction {
    #[serde(rename = "type")]
    pub kind: String,
    pub target: IrElementCriteria,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub params: Option<serde_json::Value>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub wait_after: Option<IrWaitSpec>,
}

// ---------------------------------------------------------------------------
// State / transition / document
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct IrStateCondition {
    pub element: IrElementCriteria,
    /// "visible" | "enabled" | "checked" | "expanded" | "selected" | "text" | "value"
    pub property: String,
    pub expected: serde_json::Value,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub comparator: Option<String>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct IrState {
    pub id: String,
    pub name: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,

    pub assertions: Vec<IrAssertion>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub excluded_elements: Option<Vec<IrElementCriteria>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub conditions: Option<Vec<IrStateCondition>>,

    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub is_initial: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub is_terminal: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub blocking: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub group: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub path_cost: Option<f64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub precondition: Option<String>,

    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub element_ids: Option<Vec<String>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub incoming_transitions: Option<Vec<String>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub metadata: Option<IrMetadata>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub provenance: Option<IrProvenance>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cross_refs: Option<Vec<IrCrossRef>>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct IrTransition {
    pub id: String,
    pub name: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,

    pub from_states: Vec<String>,
    pub activate_states: Vec<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub exit_states: Option<Vec<String>>,

    pub actions: Vec<IrTransitionAction>,

    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub path_cost: Option<f64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub bidirectional: Option<bool>,

    /// "read" | "write" | "destructive"
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub effect: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub metadata: Option<IrMetadata>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub provenance: Option<IrProvenance>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cross_refs: Option<Vec<IrCrossRef>>,
}

/// Top-level IR page specification (formerly `IrDocument`).
///
/// One `IrPageSpec` corresponds to one `state-machine.derived.json` file on
/// disk under `qontinui-runner/specs/pages/<id>/`. This is the authoring
/// surface — the projection layer derives the runtime `LegacySpec` from this.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct IrPageSpec {
    /// Schema version. Currently always `"1.0"`.
    pub version: String,
    pub id: String,
    pub name: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub metadata: Option<IrMetadata>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub provenance: Option<IrProvenance>,

    pub states: Vec<IrState>,
    pub transitions: Vec<IrTransition>,

    /// Groups produced by workflow-criteria synthesis (NOT derived from
    /// `IRState` annotations). Mirror of TS `IRDocument.synthesizedGroups`.
    /// The `rename = "synthesizedGroups"` is explicit (rather than relying on
    /// `rename_all = "camelCase"`) so the serialized name is unambiguous in
    /// snapshot tests + cross-language fixtures.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        rename = "synthesizedGroups"
    )]
    pub synthesized_groups: Option<Vec<IrGroup>>,

    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub initial_state: Option<String>,
}

// ---------------------------------------------------------------------------
// IR-side groups + assertions (mirror of `qontinui-schemas/ts/src/ui-bridge-ir/group.ts`).
//
// These are NOT the legacy `*.spec.uibridge.json` shapes — those live below
// (`LegacyGroup`, `LegacyAssertion`). The IR carries a free-form group channel
// for synthesis output that the projection appends after state-derived groups.
// ---------------------------------------------------------------------------

/// Mirror of TS `IRAssertionTarget`. Always `type: "search"` for synthesis-
/// emitted assertions; the wider legacy schema also supports point/region
/// targets but the IR doesn't express those today.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq)]
pub struct IrAssertionTarget {
    /// Always `"search"` for synthesis-emitted assertions.
    #[serde(rename = "type")]
    pub kind: String,
    /// Free-form criteria object — kept as `Value` so synthesis can emit
    /// partially-populated criteria without tripping the schema and so the
    /// projection can pass the bytes through verbatim.
    pub criteria: serde_json::Value,
    pub label: String,
}

/// Mirror of TS `IRAssertion`. Field shape matches `LegacyAssertion` one-to-one
/// (modulo the `target.criteria` looseness).
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct IrAssertion {
    pub id: String,
    pub description: String,
    pub category: String,
    pub severity: String,
    pub assertion_type: String,
    pub target: IrAssertionTarget,
    pub source: String,
    pub reviewed: bool,
    pub enabled: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub precondition: Option<String>,
}

/// Mirror of TS `IRGroup`. Synthesis-produced groups (NOT derived from IR
/// states). Mirrors the legacy `SpecGroup` shape so the projection can pass
/// it through to legacy `groups[]` without loss.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq)]
pub struct IrGroup {
    pub id: String,
    pub name: String,
    pub description: String,
    pub category: String,
    pub assertions: Vec<IrAssertion>,
    /// Provenance of the group itself (typically `"ai-generated"` for
    /// synthesis output).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub source: Option<String>,
    /// Free-form tags. Synthesis emits e.g.
    /// `["workflow-generated", "acceptance-criteria"]`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tags: Option<Vec<String>>,
}

// ---------------------------------------------------------------------------
// Legacy spec shapes — output of the projection (mirrors `LegacySpec` in
// `qontinui-schemas/ts/src/ui-bridge-ir/projection.ts`).
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq)]
pub struct LegacyAssertionTarget {
    /// Always `"search"` for the projection — point/region targets aren't
    /// expressible in the IR.
    #[serde(rename = "type")]
    pub kind: String,
    /// Free-form criteria object — kept as `Value` so we don't lose any
    /// inverse-projection round-trip information.
    pub criteria: serde_json::Value,
    pub label: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct LegacyAssertion {
    pub id: String,
    pub description: String,
    pub category: String,
    pub severity: String,
    pub assertion_type: String,
    pub target: LegacyAssertionTarget,
    pub source: String,
    pub reviewed: bool,
    pub enabled: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub precondition: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq)]
pub struct LegacyGroup {
    pub id: String,
    pub name: String,
    pub description: String,
    pub category: String,
    pub assertions: Vec<LegacyAssertion>,
    pub source: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct LegacyProcessStep {
    pub action: String,
    pub target: serde_json::Value,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub wait_after: Option<IrWaitSpec>,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct LegacyTransition {
    pub id: String,
    pub name: String,
    pub activate_states: Vec<String>,
    pub deactivate_states: Vec<String>,
    pub stays_visible: bool,
    pub process: Vec<LegacyProcessStep>,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct LegacyStateMachineState {
    pub id: String,
    pub name: String,
    pub description: String,
    pub elements: Vec<serde_json::Value>,
    pub is_initial: bool,
    pub transitions: Vec<LegacyTransition>,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq)]
pub struct LegacyStateMachine {
    pub states: Vec<LegacyStateMachineState>,
}

/// Top-level legacy spec output. Serialized via a `serde_json::Value` step
/// so the projection can apply lexicographic key sorting at the end (matches
/// the TS projection's `sortKeys` pass).
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct LegacySpec {
    pub version: String,
    pub description: String,
    pub groups: Vec<LegacyGroup>,
    pub state_machine: LegacyStateMachine,
    pub metadata: serde_json::Value,
}

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

    #[test]
    fn provenance_without_status_round_trips_byte_identical() {
        // Legacy spec on-disk shape: no `status` field. Must survive a
        // from_str -> to_string round trip without gaining one.
        let json = r#"{"source":"hand-authored","file":"a.tsx","line":12}"#;
        let parsed: IrProvenance = serde_json::from_str(json).unwrap();
        assert_eq!(parsed.status, None);
        let reserialized = serde_json::to_string(&parsed).unwrap();
        assert_eq!(reserialized, json);
    }

    #[test]
    fn provenance_with_proposed_status_round_trips() {
        let json = r#"{"source":"ai-generated","status":"proposed"}"#;
        let parsed: IrProvenance = serde_json::from_str(json).unwrap();
        assert_eq!(parsed.status, Some(ProposalStatus::Proposed));
        let reserialized = serde_json::to_string(&parsed).unwrap();
        assert_eq!(reserialized, json);
    }

    #[test]
    fn proposal_status_kebab_case_variants() {
        // Every variant deserializes from its kebab-case wire form and
        // round-trips back to it. Catches accidental rename_all drift.
        for (wire, variant) in [
            ("\"proposed\"", ProposalStatus::Proposed),
            ("\"pending\"", ProposalStatus::Pending),
            ("\"promoted\"", ProposalStatus::Promoted),
        ] {
            let parsed: ProposalStatus = serde_json::from_str(wire).unwrap();
            assert_eq!(parsed, variant);
            assert_eq!(serde_json::to_string(&parsed).unwrap(), wire);
        }
    }
}