Skip to main content

kaizen/sync/
canonical.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2//! Per-item canonical telemetry payloads: expand [`IngestExportBatch`](crate::sync::IngestExportBatch)
3//! for exporters, future provider pull, and goldens. Primary POST / outbox stay batch-oriented.
4
5use crate::core::identity::ActorIdentity;
6use crate::sync::outbound::OutboundEvent;
7use crate::sync::smart::{OutboundRepoSnapshotChunk, OutboundToolSpan};
8use serde::{Deserialize, Serialize};
9
10/// Forward evolution marker on exported or pulled items (read old payloads only in migration tools).
11pub const KAIZEN_SCHEMA_VERSION: u32 = 1;
12
13/// Shared context on every expanded item; identity is `None` until session/workspace wiring fills it.
14#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
15pub struct CanonicalEnvelope {
16    pub kaizen_schema_version: u32,
17    pub team_id: String,
18    pub workspace_hash: String,
19    #[serde(skip_serializing_if = "Option::is_none")]
20    pub identity: Option<ActorIdentity>,
21}
22
23/// One logical event name for third-party and docs (`print-schema` in a later phase).
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
25#[serde(rename_all = "snake_case")]
26pub enum CanonicalEventName {
27    /// One outbound event row.
28    Event,
29    /// One tool span.
30    ToolSpan,
31    /// One repo graph snapshot chunk.
32    RepoSnapshotChunk,
33    /// Skills / rules / workspace metadata (Phase 6 producer).
34    WorkspaceFactSnapshot,
35}
36
37/// Fully expanded item for a single `OutboundEvent` row.
38#[derive(Debug, Clone, Serialize, Deserialize)]
39pub struct EventItem {
40    pub envelope: CanonicalEnvelope,
41    pub name: CanonicalEventName,
42    pub event: OutboundEvent,
43}
44
45/// One tool span with batch context.
46#[derive(Debug, Clone, Serialize, Deserialize)]
47pub struct ToolSpanItem {
48    pub envelope: CanonicalEnvelope,
49    pub name: CanonicalEventName,
50    pub span: OutboundToolSpan,
51}
52
53/// One repo snapshot chunk with batch context.
54#[derive(Debug, Clone, Serialize, Deserialize)]
55pub struct RepoSnapshotChunkItem {
56    pub envelope: CanonicalEnvelope,
57    pub name: CanonicalEventName,
58    pub chunk: OutboundRepoSnapshotChunk,
59}
60
61/// Workspace-level facts (hashed skill/rule slugs from `.cursor/skills` and `.cursor/rules` discovery).
62#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
63pub struct WorkspaceFactSnapshotItem {
64    /// Redacted or hashed slugs / labels only by default.
65    pub skill_slugs: Vec<String>,
66    pub rule_slugs: Vec<String>,
67}
68
69/// Union of all canonical item shapes for `expand_ingest_batch` and mappers.
70#[derive(Debug, Clone, Serialize, Deserialize)]
71#[serde(tag = "kind", rename_all = "snake_case")]
72pub enum CanonicalItem {
73    Event(EventItem),
74    ToolSpan(ToolSpanItem),
75    RepoSnapshotChunk(RepoSnapshotChunkItem),
76    /// Populated in Phase 6; expand does not emit this from ingest batches.
77    WorkspaceFactSnapshot {
78        envelope: CanonicalEnvelope,
79        name: CanonicalEventName,
80        payload: WorkspaceFactSnapshotItem,
81    },
82}
83
84/// Expand a redacted ingest batch to one struct per event/span/chunk; never drops rows.
85pub fn expand_ingest_batch(batch: &crate::sync::IngestExportBatch) -> Vec<CanonicalItem> {
86    use crate::sync::IngestExportBatch;
87    let mut out: Vec<CanonicalItem> = Vec::new();
88    match batch {
89        IngestExportBatch::Events(b) => {
90            let env = canonical_envelope(&b.team_id, &b.workspace_hash);
91            for e in &b.events {
92                out.push(CanonicalItem::Event(EventItem {
93                    envelope: env.clone(),
94                    name: CanonicalEventName::Event,
95                    event: e.clone(),
96                }));
97            }
98        }
99        IngestExportBatch::ToolSpans(b) => {
100            let env = canonical_envelope(&b.team_id, &b.workspace_hash);
101            for span in &b.spans {
102                out.push(CanonicalItem::ToolSpan(ToolSpanItem {
103                    envelope: env.clone(),
104                    name: CanonicalEventName::ToolSpan,
105                    span: span.clone(),
106                }));
107            }
108        }
109        IngestExportBatch::RepoSnapshots(b) => {
110            let env = canonical_envelope(&b.team_id, &b.workspace_hash);
111            for chunk in &b.snapshots {
112                out.push(CanonicalItem::RepoSnapshotChunk(RepoSnapshotChunkItem {
113                    envelope: env.clone(),
114                    name: CanonicalEventName::RepoSnapshotChunk,
115                    chunk: chunk.clone(),
116                }));
117            }
118        }
119        IngestExportBatch::WorkspaceFacts(b) => {
120            let env = canonical_envelope(&b.team_id, &b.workspace_hash);
121            for row in &b.facts {
122                out.push(CanonicalItem::WorkspaceFactSnapshot {
123                    envelope: env.clone(),
124                    name: CanonicalEventName::WorkspaceFactSnapshot,
125                    payload: WorkspaceFactSnapshotItem {
126                        skill_slugs: row.skill_slugs.clone(),
127                        rule_slugs: row.rule_slugs.clone(),
128                    },
129                });
130            }
131        }
132    }
133    out
134}
135
136impl CanonicalItem {
137    /// Short name for third-party tags / metrics (`kaizen.event`, `kaizen.tool_span`, …).
138    pub fn telemetry_kind(&self) -> &'static str {
139        match self {
140            CanonicalItem::Event(_) => "kaizen.event",
141            CanonicalItem::ToolSpan(_) => "kaizen.tool_span",
142            CanonicalItem::RepoSnapshotChunk(_) => "kaizen.repo_snapshot_chunk",
143            CanonicalItem::WorkspaceFactSnapshot { .. } => "kaizen.workspace_fact_snapshot",
144        }
145    }
146
147    /// Schema version for assertions and exporters; workspace fact variant included.
148    pub fn envelope_kaizen_schema_version(&self) -> Option<u32> {
149        match self {
150            CanonicalItem::Event(i) => Some(i.envelope.kaizen_schema_version),
151            CanonicalItem::ToolSpan(i) => Some(i.envelope.kaizen_schema_version),
152            CanonicalItem::RepoSnapshotChunk(i) => Some(i.envelope.kaizen_schema_version),
153            CanonicalItem::WorkspaceFactSnapshot { envelope, .. } => {
154                Some(envelope.kaizen_schema_version)
155            }
156        }
157    }
158}
159
160fn canonical_envelope(team_id: &str, workspace_hash: &str) -> CanonicalEnvelope {
161    CanonicalEnvelope {
162        kaizen_schema_version: KAIZEN_SCHEMA_VERSION,
163        team_id: team_id.to_string(),
164        workspace_hash: workspace_hash.to_string(),
165        identity: None,
166    }
167}
168
169#[cfg(test)]
170mod tests {
171    use super::*;
172    use crate::sync::IngestExportBatch;
173    use crate::sync::outbound::EventsBatchBody;
174    use crate::sync::smart::{OutboundToolSpan, ToolSpansBatchBody};
175
176    #[test]
177    fn expand_events_one_per_row() {
178        let b = IngestExportBatch::Events(EventsBatchBody {
179            team_id: "t1".into(),
180            workspace_hash: "wh".into(),
181            events: vec![
182                OutboundEvent {
183                    session_id_hash: "s1".into(),
184                    event_seq: 0,
185                    ts_ms: 1,
186                    agent: "a".into(),
187                    model: "m".into(),
188                    kind: "message".into(),
189                    source: "hook".into(),
190                    tool: None,
191                    tool_call_id: None,
192                    tokens_in: None,
193                    tokens_out: None,
194                    reasoning_tokens: None,
195                    cost_usd_e6: None,
196                    payload: serde_json::json!({}),
197                },
198                OutboundEvent {
199                    session_id_hash: "s1".into(),
200                    event_seq: 1,
201                    ts_ms: 2,
202                    agent: "a".into(),
203                    model: "m".into(),
204                    kind: "message".into(),
205                    source: "hook".into(),
206                    tool: None,
207                    tool_call_id: None,
208                    tokens_in: None,
209                    tokens_out: None,
210                    reasoning_tokens: None,
211                    cost_usd_e6: None,
212                    payload: serde_json::json!({}),
213                },
214            ],
215        });
216        let v = expand_ingest_batch(&b);
217        assert_eq!(v.len(), 2);
218        assert_eq!(
219            v[0].envelope_kaizen_schema_version().unwrap(),
220            KAIZEN_SCHEMA_VERSION
221        );
222    }
223
224    #[test]
225    fn expand_tool_spans_n_items() {
226        let b = IngestExportBatch::ToolSpans(ToolSpansBatchBody {
227            team_id: "t".into(),
228            workspace_hash: "w".into(),
229            spans: vec![OutboundToolSpan {
230                session_id_hash: "sh".into(),
231                span_id_hash: "ph".into(),
232                tool: None,
233                status: "ok".into(),
234                started_at_ms: None,
235                ended_at_ms: None,
236                lead_time_ms: None,
237                tokens_in: None,
238                tokens_out: None,
239                reasoning_tokens: None,
240                cost_usd_e6: None,
241                path_hashes: vec![],
242            }],
243        });
244        let v = expand_ingest_batch(&b);
245        assert_eq!(v.len(), 1);
246        assert!(matches!(v[0], CanonicalItem::ToolSpan(_)));
247    }
248
249    #[test]
250    fn expand_workspace_facts_one_per_row() {
251        use crate::sync::smart::{OutboundWorkspaceFactRow, WorkspaceFactsBatchBody};
252        let b = IngestExportBatch::WorkspaceFacts(WorkspaceFactsBatchBody {
253            team_id: "t".into(),
254            workspace_hash: "w".into(),
255            facts: vec![OutboundWorkspaceFactRow {
256                skill_slugs: vec!["a".into()],
257                rule_slugs: vec!["b".into()],
258            }],
259        });
260        let v = expand_ingest_batch(&b);
261        assert_eq!(v.len(), 1);
262        assert!(matches!(v[0], CanonicalItem::WorkspaceFactSnapshot { .. }));
263    }
264}