vasari-core 0.2.2

Content-addressed intent-graph library behind Vasari — intent attribution for autonomous coding agents.
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
/// Adapter for OTLP JSON exports with GenAI semantic conventions ≥ 1.30.0.
///
/// Reads a single OTLP JSON file (or stdin) and reconstructs the span tree
/// via a two-pass algorithm — OTLP exports are not topologically sorted, so
/// we index all spans by spanId first, then walk from roots down.
///
/// GenAI spans of interest:
///   gen_ai.operation.name = "chat" | "generate" | "complete" | "stream"
///   gen_ai.system           — model vendor ("anthropic", "openai", …)
///   gen_ai.request.model    — model name
///   gen_ai.prompt           — user prompt text (deprecated but widely used)
///   gen_ai.completion       — model completion text (deprecated but widely used)
///
/// Mapping to Vasari nodes:
///   root span (no parentSpanId, gen_ai op) → SessionStart + UserPrompt
///   child spans                             → ToolCall events
use std::collections::HashMap;
use std::io::{BufReader, Read};

use chrono::{DateTime, TimeZone, Utc};
use serde_json::Value;

use crate::{
    error::VasariError,
    ingest::{IngestAdapter, IngestEvent, IngestSource},
};

pub struct OtelGenAiAdapter;

impl IngestAdapter for OtelGenAiAdapter {
    fn parse(&self, source: IngestSource) -> Result<Vec<IngestEvent>, VasariError> {
        let mut buf = String::new();
        match source {
            IngestSource::File(path) => {
                std::fs::File::open(&path)
                    .map_err(VasariError::Io)?
                    .read_to_string(&mut buf)
                    .map_err(VasariError::Io)?;
            }
            IngestSource::Stdin => {
                BufReader::new(std::io::stdin())
                    .read_to_string(&mut buf)
                    .map_err(VasariError::Io)?;
            }
        }
        parse_otlp_json(&buf)
    }
}

fn parse_otlp_json(json: &str) -> Result<Vec<IngestEvent>, VasariError> {
    let root: Value = serde_json::from_str(json)?;

    // Collect all spans from resourceSpans[*].scopeSpans[*].spans[*]
    let mut all_spans: Vec<Value> = Vec::new();

    if let Some(resource_spans) = root.get("resourceSpans").and_then(|v| v.as_array()) {
        for rs in resource_spans {
            if let Some(scope_spans) = rs.get("scopeSpans").and_then(|v| v.as_array()) {
                for ss in scope_spans {
                    if let Some(spans) = ss.get("spans").and_then(|v| v.as_array()) {
                        all_spans.extend(spans.iter().cloned());
                    }
                }
            }
        }
    }

    if all_spans.is_empty() {
        return Ok(vec![]);
    }

    // Pass 1: index by spanId
    let mut by_span_id: HashMap<String, &Value> = HashMap::new();
    for span in &all_spans {
        if let Some(id) = span.get("spanId").and_then(|v| v.as_str()) {
            by_span_id.insert(id.to_string(), span);
        }
    }

    // Pass 2: walk from roots (no parentSpanId or parentSpanId not in index)
    let roots: Vec<&Value> = all_spans
        .iter()
        .filter(|span| {
            span.get("parentSpanId")
                .and_then(|v| v.as_str())
                .map(|pid| pid.is_empty() || !by_span_id.contains_key(pid))
                .unwrap_or(true)
        })
        .collect();

    let mut events: Vec<IngestEvent> = Vec::new();
    let mut saw_session_start = false;

    let earliest_ts = all_spans
        .iter()
        .filter_map(|s| s.get("startTimeUnixNano").and_then(parse_unix_nano))
        .min()
        .unwrap_or_else(Utc::now);

    for root_span in roots {
        let span_start = root_span
            .get("startTimeUnixNano")
            .and_then(parse_unix_nano)
            .unwrap_or(earliest_ts);

        let attrs = span_attrs(root_span);
        let op = attrs.get("gen_ai.operation.name").map(|s| s.as_str());
        let system = attrs.get("gen_ai.system").map(|s| s.as_str());
        let model = attrs.get("gen_ai.request.model").map(|s| s.as_str());

        // Only process spans that look like GenAI operations.
        let is_gen_ai = op.is_some() || system.is_some() || attrs.contains_key("gen_ai.prompt");
        if !is_gen_ai {
            continue;
        }

        // Emit SessionStart from the first root GenAI span.
        if !saw_session_start {
            let source_label = format!(
                "otel:{}:{}",
                system.unwrap_or("unknown"),
                model.unwrap_or("unknown")
            );
            events.push(IngestEvent::SessionStart {
                source: source_label,
                started_at: earliest_ts,
            });
            saw_session_start = true;
        }

        // UserPrompt from gen_ai.prompt attribute.
        if let Some(prompt) = attrs.get("gen_ai.prompt") {
            let text = prompt.trim().to_string();
            if !text.is_empty() {
                events.push(IngestEvent::UserPrompt {
                    text,
                    timestamp: span_start,
                });
            }
        }

        // Walk children.
        let span_id = root_span
            .get("spanId")
            .and_then(|v| v.as_str())
            .unwrap_or("");

        let children: Vec<&Value> = all_spans
            .iter()
            .filter(|s| {
                s.get("parentSpanId")
                    .and_then(|v| v.as_str())
                    .map(|pid| pid == span_id)
                    .unwrap_or(false)
            })
            .collect();

        for child in children {
            if let Some(ev) = child_span_to_event(child) {
                events.push(ev);
            }
        }

        // Completion as SystemInstruction so constraints are extracted.
        if let Some(completion) = attrs.get("gen_ai.completion") {
            let text = completion.trim().to_string();
            if !text.is_empty() {
                events.push(IngestEvent::SystemInstruction { text });
            }
        }
    }

    // Orphan spans: parent was referenced but not present in the export.
    // Emit them as ToolCalls so we don't silently drop recorded work.
    for span in &all_spans {
        let parent = span
            .get("parentSpanId")
            .and_then(|v| v.as_str())
            .unwrap_or("");
        if !parent.is_empty() && !by_span_id.contains_key(parent) {
            if let Some(ev) = child_span_to_event(span) {
                events.push(ev);
            }
        }
    }

    Ok(events)
}

/// Map a child span to a ToolCall IngestEvent.
fn child_span_to_event(span: &Value) -> Option<IngestEvent> {
    let name = span
        .get("name")
        .and_then(|v| v.as_str())
        .unwrap_or("unknown");
    let attrs = span_attrs(span);
    let timestamp = span
        .get("startTimeUnixNano")
        .and_then(parse_unix_nano)
        .unwrap_or_else(Utc::now);

    let result_summary = attrs
        .get("gen_ai.completion")
        .map(|s| s.to_string())
        .unwrap_or_default();

    let mut args = serde_json::Map::new();
    for (k, v) in &attrs {
        args.insert(k.clone(), Value::String(v.clone()));
    }

    Some(IngestEvent::ToolCall {
        name: name.to_string(),
        args: Value::Object(args),
        result_summary,
        timestamp,
        // OTEL GenAI spans carry no free-text agent rationale.
        rationale: None,
    })
}

/// Extract span attributes into a flat String→String map.
fn span_attrs(span: &Value) -> HashMap<String, String> {
    let mut map = HashMap::new();
    if let Some(attrs) = span.get("attributes").and_then(|v| v.as_array()) {
        for attr in attrs {
            let key = attr.get("key").and_then(|v| v.as_str()).unwrap_or("");
            if key.is_empty() {
                continue;
            }
            if let Some(val) = attr.get("value") {
                let str_val = extract_attr_value(val);
                if !str_val.is_empty() {
                    map.insert(key.to_string(), str_val);
                }
            }
        }
    }
    map
}

/// OTLP attribute values are typed: { "stringValue": "…" } | { "intValue": "…" } | etc.
fn extract_attr_value(val: &Value) -> String {
    if let Some(s) = val.get("stringValue").and_then(|v| v.as_str()) {
        return s.to_string();
    }
    if let Some(i) = val.get("intValue").and_then(|v| v.as_i64()) {
        return i.to_string();
    }
    if let Some(i) = val.get("intValue").and_then(|v| v.as_str()) {
        return i.to_string();
    }
    if let Some(d) = val.get("doubleValue").and_then(|v| v.as_f64()) {
        return d.to_string();
    }
    if let Some(b) = val.get("boolValue").and_then(|v| v.as_bool()) {
        return b.to_string();
    }
    String::new()
}

/// Parse an OTLP Unix nanosecond timestamp (string or number) into DateTime<Utc>.
fn parse_unix_nano(val: &Value) -> Option<DateTime<Utc>> {
    let nanos: i64 = if let Some(s) = val.as_str() {
        s.parse().ok()?
    } else if let Some(n) = val.as_i64() {
        n
    } else if let Some(n) = val.as_u64() {
        n as i64
    } else {
        return None;
    };
    let secs = nanos / 1_000_000_000;
    let nsecs = (nanos % 1_000_000_000) as u32;
    Utc.timestamp_opt(secs, nsecs).single()
}

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

    fn minimal_otlp(prompt: &str) -> String {
        format!(
            r#"{{
  "resourceSpans": [{{
    "resource": {{"attributes": []}},
    "scopeSpans": [{{
      "scope": {{"name": "opentelemetry-anthropic", "version": "0.1.0"}},
      "spans": [{{
        "traceId": "abcdef1234567890abcdef1234567890",
        "spanId": "1234567890abcdef",
        "name": "gen_ai.chat",
        "startTimeUnixNano": "1704067200000000000",
        "endTimeUnixNano": "1704067205000000000",
        "attributes": [
          {{"key": "gen_ai.system", "value": {{"stringValue": "anthropic"}}}},
          {{"key": "gen_ai.operation.name", "value": {{"stringValue": "chat"}}}},
          {{"key": "gen_ai.request.model", "value": {{"stringValue": "claude-3-5-sonnet"}}}},
          {{"key": "gen_ai.prompt", "value": {{"stringValue": "{prompt}"}}}}
        ]
      }}]
    }}]
  }}]
}}"#
        )
    }

    #[test]
    fn parses_minimal_otlp() {
        let json = minimal_otlp("Add JWT verification to the auth module");
        let events = parse_otlp_json(&json).unwrap();

        let has_session = events
            .iter()
            .any(|e| matches!(e, IngestEvent::SessionStart { .. }));
        let has_prompt = events
            .iter()
            .any(|e| matches!(e, IngestEvent::UserPrompt { text, .. } if text.contains("JWT")));

        assert!(has_session, "should have SessionStart");
        assert!(has_prompt, "should have UserPrompt from gen_ai.prompt");
    }

    #[test]
    fn empty_spans_produces_empty_events() {
        let json = r#"{"resourceSpans": []}"#;
        let events = parse_otlp_json(json).unwrap();
        assert!(events.is_empty());
    }

    #[test]
    fn non_gen_ai_spans_are_skipped() {
        let json = r#"{
  "resourceSpans": [{
    "scopeSpans": [{
      "spans": [{
        "spanId": "abc123",
        "name": "http.request",
        "startTimeUnixNano": "1704067200000000000",
        "attributes": [
          {"key": "http.method", "value": {"stringValue": "GET"}}
        ]
      }]
    }]
  }]
}"#;
        let events = parse_otlp_json(json).unwrap();
        assert!(
            events.is_empty(),
            "non-gen_ai spans should produce no events"
        );
    }

    #[test]
    fn orphan_span_becomes_tool_call() {
        // A span whose parentSpanId is not in the export (orphan)
        let json = r#"{
  "resourceSpans": [{
    "scopeSpans": [{
      "spans": [{
        "spanId": "orphan001",
        "parentSpanId": "missing001",
        "name": "tool.call",
        "startTimeUnixNano": "1704067200000000000",
        "attributes": [
          {"key": "gen_ai.operation.name", "value": {"stringValue": "tool"}}
        ]
      }]
    }]
  }]
}"#;
        let events = parse_otlp_json(json).unwrap();
        let tool_calls: Vec<_> = events
            .iter()
            .filter(|e| matches!(e, IngestEvent::ToolCall { .. }))
            .collect();
        assert!(
            !tool_calls.is_empty(),
            "orphan span should become a ToolCall"
        );
    }

    #[test]
    fn gen_ai_completion_becomes_system_instruction() {
        let json = r#"{
  "resourceSpans": [{
    "scopeSpans": [{
      "spans": [{
        "spanId": "root001",
        "name": "gen_ai.chat",
        "startTimeUnixNano": "1704067200000000000",
        "attributes": [
          {"key": "gen_ai.operation.name", "value": {"stringValue": "chat"}},
          {"key": "gen_ai.prompt", "value": {"stringValue": "Implement JWT auth"}},
          {"key": "gen_ai.completion", "value": {"stringValue": "I will add JWT verification to your module."}}
        ]
      }]
    }]
  }]
}"#;
        let events = parse_otlp_json(json).unwrap();
        let sys: Vec<_> = events
            .iter()
            .filter(|e| matches!(e, IngestEvent::SystemInstruction { text } if text.contains("JWT verification")))
            .collect();
        assert!(
            !sys.is_empty(),
            "gen_ai.completion should become SystemInstruction"
        );
    }

    #[test]
    fn extract_attr_value_int_as_string() {
        // OTLP sometimes encodes int64 as a JSON string
        let val = serde_json::json!({"intValue": "42"});
        assert_eq!(extract_attr_value(&val), "42");
    }

    #[test]
    fn extract_attr_value_double() {
        let val = serde_json::json!({"doubleValue": 2.5});
        assert_eq!(extract_attr_value(&val), "2.5");
    }

    #[test]
    fn extract_attr_value_bool() {
        let val = serde_json::json!({"boolValue": true});
        assert_eq!(extract_attr_value(&val), "true");
    }

    #[test]
    fn parse_unix_nano_string_form() {
        let val = serde_json::json!("1704067200000000000");
        let dt = parse_unix_nano(&val).unwrap();
        assert_eq!(dt.timestamp(), 1704067200);
    }

    #[test]
    fn parse_unix_nano_u64_form() {
        let val = serde_json::json!(1704067200000000000u64);
        let dt = parse_unix_nano(&val).unwrap();
        assert_eq!(dt.timestamp(), 1704067200);
    }

    #[test]
    fn two_pass_reconstructs_parent_child() {
        // Child span appears before parent in the export (unsorted).
        let json = r#"{
  "resourceSpans": [{
    "scopeSpans": [{
      "spans": [
        {
          "spanId": "child0001",
          "parentSpanId": "root0001",
          "name": "tool.use",
          "startTimeUnixNano": "1704067201000000000",
          "attributes": []
        },
        {
          "spanId": "root0001",
          "name": "gen_ai.chat",
          "startTimeUnixNano": "1704067200000000000",
          "attributes": [
            {"key": "gen_ai.operation.name", "value": {"stringValue": "chat"}},
            {"key": "gen_ai.prompt", "value": {"stringValue": "Implement auth"}}
          ]
        }
      ]
    }]
  }]
}"#;
        let events = parse_otlp_json(json).unwrap();
        let has_session = events
            .iter()
            .any(|e| matches!(e, IngestEvent::SessionStart { .. }));
        let has_prompt = events
            .iter()
            .any(|e| matches!(e, IngestEvent::UserPrompt { .. }));
        let has_tool = events
            .iter()
            .any(|e| matches!(e, IngestEvent::ToolCall { .. }));
        assert!(has_session);
        assert!(has_prompt);
        assert!(has_tool, "child span should become ToolCall");
    }
}