car-eventlog 0.24.0

Event log with JSONL persistence for Common Agent Runtime
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
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
//! Event log with JSONL persistence for Common Agent Runtime.
//!
//! Append-only event log. Every runtime operation is recorded here.
//! Supports optional JSONL journal persistence for replay and audit.

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;
use std::fs::{self, OpenOptions};
use std::io::{BufRead, BufReader, BufWriter, Write};
use std::path::{Path, PathBuf};
use std::sync::mpsc;
use std::thread;
use uuid::Uuid;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EventLogStats {
    pub events: usize,
    pub spans: usize,
    pub approx_event_bytes: usize,
    pub approx_span_bytes: usize,
}

/// Event kinds matching the Python EventKind enum.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EventKind {
    ProposalReceived,
    ActionValidated,
    ActionRejected,
    ActionExecuting,
    ActionSucceeded,
    ActionFailed,
    ActionSkipped,
    ActionRetrying,
    ActionDeduplicated,
    PolicyViolation,
    StateChanged,
    StateSnapshot,
    StateRollback,
    // Skill lifecycle events (SkillRL-inspired)
    SkillDistilled,
    SkillEvolved,
    SkillDeprecated,
    EvolutionTriggered,
    /// A provisional skill candidate passed the validation gate and was promoted
    /// to Active, superseding its incumbent (SkillOpt-inspired — see
    /// `docs/solutions/gated-skill-optimization.md`).
    CandidatePromoted,
    /// A provisional skill candidate failed the validation gate and was rejected
    /// (recorded in the rejected-edit buffer so it isn't regenerated).
    CandidateRejected,
    // Memory consolidation ("dream") events
    Consolidated,
    // Replanning events
    ReplanAttempted,
    ReplanProposalReceived,
    ReplanRejected,
    ReplanExhausted,
    // Voice turn telemetry — emitted by car-engine's voice_turn dispatch
    // and the orchestrator. `data` carries `turn_id` (u64) plus
    // event-specific fields like `text_len`, `error`, `timeout_ms`.
    VoiceFastTurnStarted,
    VoiceFastTurnEnded,
    VoiceSidecarResolved,
    VoiceSidecarFailed,
    VoiceSidecarTimedOut,
    VoiceTurnCancelled,
    VoiceBridgePlayed,
    // Foreman merge-verify gate (verified-parallel-coding-orchestrator).
    // Emitted by car-multi's foreman gate when a farmed-out worktree is
    // verified before integration. `data` carries `subtask`, `changed_symbols`,
    // `containment_violations`, `semantic_conflicts`, and `build_test`. This is
    // the audit trail that makes the gate policy-aware rather than a bare merge.
    GateAccepted,
    GateRejected,
    // Per-execution caller / tenant scope (Parslee-ai/car#187 phase 3).
    // Emitted by Runtime::execute_scoped* once per proposal when the
    // RuntimeScope carries any identity. `data` carries `caller_id`,
    // `tenant_id`, and `claims` — exact set depends on what the
    // dispatcher forwarded. Audit / log analysis correlates actions
    // back to the caller / tenant that triggered them.
    SessionScope,
}

/// Status of a trace span.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum SpanStatus {
    Ok,
    Error,
    Unset,
}

/// A trace span representing a unit of work.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Span {
    pub trace_id: String,
    pub span_id: String,
    pub parent_span_id: Option<String>,
    pub name: String,
    pub start_time: DateTime<Utc>,
    pub end_time: Option<DateTime<Utc>>,
    pub status: SpanStatus,
    pub attributes: HashMap<String, Value>,
}

/// A single event in the log.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Event {
    pub kind: EventKind,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub action_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub proposal_id: Option<String>,
    #[serde(default)]
    pub data: HashMap<String, Value>,
    #[serde(default = "Utc::now")]
    pub timestamp: DateTime<Utc>,
}

/// Background JSONL journal writer. `EventLog::append` hands a serialized event
/// line to this over a channel; a dedicated thread owns the file and does the
/// actual write. So `append` never does file I/O while a caller holds the log
/// mutex — the head-of-line blocking that bites when many concurrent tasks
/// (e.g. Foreman gate verifications running under one shared, journaled session
/// log) each re-opened and wrote the file under the lock.
///
/// Best-effort, like the journal it replaces: an open/write failure drops the
/// line (the in-memory event vec is unaffected) — but unlike the old silent
/// journal, the hard failures (can't spawn the thread, can't open the file) are
/// surfaced via `tracing::warn!`, since this carries the gate audit trail and a
/// silently-broken audit log is worse than a noisy one.
///
/// The channel is unbounded so a burst never blocks the hot path. This relies on
/// an envelope: low per-session journal volume and a writer that keeps up, so the
/// backlog stays small. It is not a *new* unbounded-growth risk — the in-memory
/// `events` vec already grows without bound under the same pathological
/// hot-loop-`append` workload, so the channel is not the first thing to OOM.
struct JournalWriter {
    /// `None` only if the writer thread could not be spawned (journaling then
    /// silently disabled — still best-effort).
    tx: Option<mpsc::Sender<String>>,
    handle: Option<thread::JoinHandle<()>>,
}

impl JournalWriter {
    fn spawn(path: PathBuf) -> Self {
        let (tx, rx) = mpsc::channel::<String>();
        match thread::Builder::new()
            .name("car-eventlog-journal".into())
            .spawn(move || journal_loop(path, rx))
        {
            Ok(handle) => Self {
                tx: Some(tx),
                handle: Some(handle),
            },
            // Drop tx (rx dies with it); journaling becomes a no-op.
            Err(e) => {
                tracing::warn!(error = %e, "car-eventlog: failed to spawn journal writer thread — journaling disabled for this log");
                Self {
                    tx: None,
                    handle: None,
                }
            }
        }
    }

    fn send(&self, line: String) {
        if let Some(tx) = &self.tx {
            // Best-effort: if the writer thread has gone, drop the line.
            let _ = tx.send(line);
        }
    }
}

impl Drop for JournalWriter {
    fn drop(&mut self) {
        // Close the channel so the writer drains its backlog, flushes, and
        // exits; join so buffered lines are durable by the time the log is gone.
        self.tx.take();
        if let Some(handle) = self.handle.take() {
            let _ = handle.join();
        }
    }
}

/// The journal thread's body: own the file, write each line, flush when the
/// channel goes momentarily idle (batches bursts, keeps durability prompt).
fn journal_loop(path: PathBuf, rx: mpsc::Receiver<String>) {
    let file = match OpenOptions::new().create(true).append(true).open(&path) {
        Ok(file) => file,
        // Can't open — surface it (this is the audit journal), then block-drain
        // so the channel doesn't accumulate if senders keep trying, and exit.
        // `recv()` blocks (it is not a spin loop) and returns Err once every
        // sender drops. Matches the prior fail-soft journal, but no longer silent.
        Err(e) => {
            tracing::warn!(path = %path.display(), error = %e, "car-eventlog: cannot open journal file — events for this log will not be persisted");
            while rx.recv().is_ok() {}
            return;
        }
    };
    let mut writer = BufWriter::new(file);
    while let Ok(line) = rx.recv() {
        let _ = writeln!(writer, "{line}");
        // Drain whatever is already queued without blocking, then flush once —
        // one fsync-free flush amortized over a burst instead of per line.
        while let Ok(more) = rx.try_recv() {
            let _ = writeln!(writer, "{more}");
        }
        let _ = writer.flush();
    }
    let _ = writer.flush();
}

/// Append-only event log with optional JSONL journal.
pub struct EventLog {
    events: Vec<Event>,
    spans: Vec<Span>,
    journal: Option<JournalWriter>,
}

impl EventLog {
    pub fn new() -> Self {
        Self {
            events: Vec::new(),
            spans: Vec::new(),
            journal: None,
        }
    }

    pub fn with_journal(path: PathBuf) -> Self {
        if let Some(parent) = path.parent() {
            let _ = fs::create_dir_all(parent);
        }
        Self {
            events: Vec::new(),
            spans: Vec::new(),
            journal: Some(JournalWriter::spawn(path)),
        }
    }

    pub fn append(
        &mut self,
        kind: EventKind,
        action_id: Option<&str>,
        proposal_id: Option<&str>,
        data: HashMap<String, Value>,
    ) -> &Event {
        let event = Event {
            kind,
            action_id: action_id.map(|s| s.to_string()),
            proposal_id: proposal_id.map(|s| s.to_string()),
            data,
            timestamp: Utc::now(),
        };

        // Hand the serialized line to the background writer — no file I/O here,
        // so a caller holding the log mutex is never blocked on disk.
        if let Some(journal) = &self.journal {
            if let Ok(json) = serde_json::to_string(&event) {
                journal.send(json);
            }
        }

        self.events.push(event);
        self.events.last().unwrap()
    }

    pub fn events(&self) -> &[Event] {
        &self.events
    }

    pub fn len(&self) -> usize {
        self.events.len()
    }

    pub fn span_len(&self) -> usize {
        self.spans.len()
    }

    pub fn is_empty(&self) -> bool {
        self.events.is_empty()
    }

    pub fn stats(&self) -> EventLogStats {
        EventLogStats {
            events: self.events.len(),
            spans: self.spans.len(),
            approx_event_bytes: approx_json_bytes(&self.events),
            approx_span_bytes: approx_json_bytes(&self.spans),
        }
    }

    pub fn truncate_events_keep_last(&mut self, keep_last: usize) -> usize {
        truncate_vec_keep_last(&mut self.events, keep_last)
    }

    pub fn truncate_spans_keep_last(&mut self, keep_last: usize) -> usize {
        truncate_vec_keep_last(&mut self.spans, keep_last)
    }

    pub fn clear(&mut self) -> EventLogStats {
        let removed = self.stats();
        self.events.clear();
        self.events.shrink_to_fit();
        self.spans.clear();
        self.spans.shrink_to_fit();
        removed
    }

    pub fn filter(&self, kind: Option<&EventKind>, action_id: Option<&str>) -> Vec<&Event> {
        self.events
            .iter()
            .filter(|e| {
                if let Some(k) = kind {
                    if &e.kind != k {
                        return false;
                    }
                }
                if let Some(aid) = action_id {
                    if e.action_id.as_deref() != Some(aid) {
                        return false;
                    }
                }
                true
            })
            .collect()
    }

    /// Begin a new trace span. Returns the generated span_id.
    pub fn begin_span(
        &mut self,
        name: &str,
        trace_id: &str,
        parent_span_id: Option<&str>,
        attributes: HashMap<String, Value>,
    ) -> String {
        let span_id = Uuid::new_v4().to_string();
        let span = Span {
            trace_id: trace_id.to_string(),
            span_id: span_id.clone(),
            parent_span_id: parent_span_id.map(|s| s.to_string()),
            name: name.to_string(),
            start_time: Utc::now(),
            end_time: None,
            status: SpanStatus::Unset,
            attributes,
        };
        self.spans.push(span);
        span_id
    }

    /// End an open span by setting its status and end time.
    pub fn end_span(&mut self, span_id: &str, status: SpanStatus) {
        if let Some(span) = self.spans.iter_mut().find(|s| s.span_id == span_id) {
            span.end_time = Some(Utc::now());
            span.status = status;
        }
    }

    /// Return all spans.
    pub fn spans(&self) -> Vec<Span> {
        self.spans.clone()
    }

    /// Export traces as OTLP-compatible JSON.
    pub fn export_traces(&self) -> String {
        // Group spans by trace_id
        let mut traces: HashMap<&str, Vec<&Span>> = HashMap::new();
        for span in &self.spans {
            traces.entry(span.trace_id.as_str()).or_default().push(span);
        }

        let resource_spans: Vec<Value> = traces
            .into_iter()
            .map(|(_trace_id, spans)| {
                let scope_spans = spans
                    .iter()
                    .map(|s| {
                        let mut span_obj = serde_json::json!({
                            "traceId": s.trace_id,
                            "spanId": s.span_id,
                            "name": s.name,
                            "startTimeUnixNano": s.start_time.timestamp_nanos_opt().unwrap_or(0).to_string(),
                            "status": {
                                "code": match s.status {
                                    SpanStatus::Ok => 1,
                                    SpanStatus::Error => 2,
                                    SpanStatus::Unset => 0,
                                }
                            },
                            "attributes": s.attributes.iter().map(|(k, v)| {
                                serde_json::json!({
                                    "key": k,
                                    "value": { "stringValue": v.to_string() }
                                })
                            }).collect::<Vec<_>>(),
                        });

                        if let Some(ref parent) = s.parent_span_id {
                            span_obj.as_object_mut().unwrap().insert(
                                "parentSpanId".to_string(),
                                Value::from(parent.as_str()),
                            );
                        }
                        if let Some(end) = s.end_time {
                            span_obj.as_object_mut().unwrap().insert(
                                "endTimeUnixNano".to_string(),
                                Value::from(end.timestamp_nanos_opt().unwrap_or(0).to_string()),
                            );
                        }

                        span_obj
                    })
                    .collect::<Vec<_>>();

                serde_json::json!({
                    "resource": {
                        "attributes": [
                            { "key": "service.name", "value": { "stringValue": "car-runtime" } }
                        ]
                    },
                    "scopeSpans": [{
                        "scope": { "name": "car-eventlog" },
                        "spans": scope_spans
                    }]
                })
            })
            .collect();

        serde_json::to_string(&serde_json::json!({
            "resourceSpans": resource_spans
        }))
        .unwrap_or_else(|_| "{}".to_string())
    }

    /// Load an event log from a JSONL journal file.
    pub fn load(path: &Path) -> std::io::Result<Self> {
        let file = fs::File::open(path)?;
        let reader = BufReader::new(file);
        let mut events = Vec::new();

        for line in reader.lines() {
            let line = line?;
            let line = line.trim();
            if !line.is_empty() {
                if let Ok(event) = serde_json::from_str::<Event>(line) {
                    events.push(event);
                }
            }
        }

        Ok(Self {
            events,
            spans: Vec::new(),
            // Subsequent appends journal back to the same file (append mode
            // preserves the loaded content) via the background writer.
            journal: Some(JournalWriter::spawn(path.to_path_buf())),
        })
    }
}

fn approx_json_bytes<T: Serialize>(value: &T) -> usize {
    serde_json::to_vec(value)
        .map(|bytes| bytes.len())
        .unwrap_or(0)
}

fn truncate_vec_keep_last<T>(items: &mut Vec<T>, keep_last: usize) -> usize {
    let len = items.len();
    if len <= keep_last {
        return 0;
    }
    let removed = len - keep_last;
    items.drain(..removed);
    items.shrink_to_fit();
    removed
}

impl Default for EventLog {
    fn default() -> Self {
        Self::new()
    }
}

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

    #[test]
    fn append_and_read() {
        let mut log = EventLog::new();
        log.append(
            EventKind::ProposalReceived,
            None,
            Some("p1"),
            [("source".to_string(), Value::from("test"))].into(),
        );
        assert_eq!(log.len(), 1);
        assert_eq!(log.events()[0].kind, EventKind::ProposalReceived);
    }

    #[test]
    fn filter_by_kind() {
        let mut log = EventLog::new();
        log.append(
            EventKind::ProposalReceived,
            None,
            Some("p1"),
            HashMap::new(),
        );
        log.append(
            EventKind::ActionValidated,
            Some("a1"),
            Some("p1"),
            HashMap::new(),
        );
        log.append(
            EventKind::ActionSucceeded,
            Some("a1"),
            Some("p1"),
            HashMap::new(),
        );

        let validated = log.filter(Some(&EventKind::ActionValidated), None);
        assert_eq!(validated.len(), 1);
    }

    #[test]
    fn filter_by_action_id() {
        let mut log = EventLog::new();
        log.append(EventKind::ActionValidated, Some("a1"), None, HashMap::new());
        log.append(EventKind::ActionValidated, Some("a2"), None, HashMap::new());

        let a1_events = log.filter(None, Some("a1"));
        assert_eq!(a1_events.len(), 1);
    }

    #[test]
    fn journal_write_and_reload() {
        let dir = tempfile::tempdir().unwrap();
        let journal = dir.path().join("events.jsonl");

        {
            let mut log = EventLog::with_journal(journal.clone());
            log.append(
                EventKind::ProposalReceived,
                None,
                Some("p1"),
                HashMap::new(),
            );
            log.append(
                EventKind::ActionSucceeded,
                Some("a1"),
                Some("p1"),
                HashMap::new(),
            );
        }

        assert!(journal.exists());

        let reloaded = EventLog::load(&journal).unwrap();
        assert_eq!(reloaded.len(), 2);
        assert_eq!(reloaded.events()[0].kind, EventKind::ProposalReceived);
        assert_eq!(reloaded.events()[1].kind, EventKind::ActionSucceeded);
    }

    #[test]
    fn journal_preserves_order_and_count_under_burst() {
        // The background writer must not lose or reorder events under a tight
        // append burst; drop-join guarantees the backlog is flushed before the
        // log is gone.
        let dir = tempfile::tempdir().unwrap();
        let journal = dir.path().join("burst.jsonl");
        {
            let mut log = EventLog::with_journal(journal.clone());
            for i in 0..500 {
                log.append(
                    EventKind::ActionSucceeded,
                    Some(&format!("a{i}")),
                    None,
                    HashMap::new(),
                );
            }
        } // drop joins the writer thread → all 500 lines flushed.

        let reloaded = EventLog::load(&journal).unwrap();
        assert_eq!(reloaded.len(), 500, "no events lost");
        for (i, event) in reloaded.events().iter().enumerate() {
            assert_eq!(
                event.action_id.as_deref(),
                Some(format!("a{i}").as_str()),
                "order preserved at {i}"
            );
        }
    }

    #[test]
    fn unopenable_journal_is_best_effort_not_fatal() {
        // The whole "best-effort" promise rests on this branch: a journal path
        // that can't be opened (here: the path IS an existing directory) must not
        // panic or block append — the in-memory log keeps working.
        let dir = tempfile::tempdir().unwrap();
        let journal = dir.path().join("a-directory");
        fs::create_dir(&journal).unwrap(); // open(append) on a dir fails

        let mut log = EventLog::with_journal(journal);
        log.append(EventKind::ProposalReceived, None, Some("p1"), HashMap::new());
        log.append(EventKind::ActionSucceeded, Some("a1"), None, HashMap::new());
        assert_eq!(log.len(), 2, "in-memory log unaffected by an unwritable journal");
        // Drop must still terminate cleanly (writer thread drained and joined).
    }

    #[test]
    fn load_then_append_preserves_existing_and_adds() {
        let dir = tempfile::tempdir().unwrap();
        let journal = dir.path().join("resume.jsonl");
        {
            let mut log = EventLog::with_journal(journal.clone());
            log.append(EventKind::ProposalReceived, None, Some("p1"), HashMap::new());
        }
        // Resume: load, append more, drop → both old and new are on disk.
        {
            let mut log = EventLog::load(&journal).unwrap();
            assert_eq!(log.len(), 1);
            log.append(EventKind::ActionSucceeded, Some("a1"), None, HashMap::new());
        }
        let reloaded = EventLog::load(&journal).unwrap();
        assert_eq!(reloaded.len(), 2, "append-mode preserved the loaded line");
        assert_eq!(reloaded.events()[0].kind, EventKind::ProposalReceived);
        assert_eq!(reloaded.events()[1].kind, EventKind::ActionSucceeded);
    }

    #[test]
    fn event_kind_serializes_snake_case() {
        assert_eq!(
            serde_json::to_string(&EventKind::ProposalReceived).unwrap(),
            "\"proposal_received\""
        );
        assert_eq!(
            serde_json::to_string(&EventKind::StateSnapshot).unwrap(),
            "\"state_snapshot\""
        );
    }

    #[test]
    fn stats_truncate_and_clear_release_retained_entries() {
        let mut log = EventLog::new();
        for idx in 0..5 {
            log.append(
                EventKind::ActionSucceeded,
                Some(&format!("a{idx}")),
                Some("p1"),
                [("payload".to_string(), Value::from("x".repeat(16)))].into(),
            );
            log.begin_span("action.tool_call", "trace", None, HashMap::new());
        }

        let stats = log.stats();
        assert_eq!(stats.events, 5);
        assert_eq!(stats.spans, 5);
        assert!(stats.approx_event_bytes > 0);
        assert!(stats.approx_span_bytes > 0);

        assert_eq!(log.truncate_events_keep_last(2), 3);
        assert_eq!(log.truncate_spans_keep_last(1), 4);
        assert_eq!(log.len(), 2);
        assert_eq!(log.span_len(), 1);
        assert_eq!(log.events()[0].action_id.as_deref(), Some("a3"));

        let removed = log.clear();
        assert_eq!(removed.events, 2);
        assert_eq!(removed.spans, 1);
        assert_eq!(log.len(), 0);
        assert_eq!(log.span_len(), 0);
    }

    #[test]
    fn span_begin_end_lifecycle() {
        let mut log = EventLog::new();
        let trace_id = "trace-1".to_string();

        let span_id = log.begin_span(
            "test.operation",
            &trace_id,
            None,
            [("key".to_string(), Value::from("value"))].into(),
        );

        let spans = log.spans();
        assert_eq!(spans.len(), 1);
        assert_eq!(spans[0].name, "test.operation");
        assert_eq!(spans[0].trace_id, "trace-1");
        assert!(spans[0].parent_span_id.is_none());
        assert!(spans[0].end_time.is_none());
        assert_eq!(spans[0].status, SpanStatus::Unset);

        log.end_span(&span_id, SpanStatus::Ok);

        let spans = log.spans();
        assert!(spans[0].end_time.is_some());
        assert_eq!(spans[0].status, SpanStatus::Ok);
    }

    #[test]
    fn span_parent_child_relationship() {
        let mut log = EventLog::new();
        let trace_id = "trace-2".to_string();

        let parent_id = log.begin_span("parent.op", &trace_id, None, HashMap::new());
        let child_id = log.begin_span("child.op", &trace_id, Some(&parent_id), HashMap::new());

        let spans = log.spans();
        assert_eq!(spans.len(), 2);

        let child = spans.iter().find(|s| s.span_id == child_id).unwrap();
        assert_eq!(child.parent_span_id.as_deref(), Some(parent_id.as_str()));
        assert_eq!(child.trace_id, trace_id);

        let parent = spans.iter().find(|s| s.span_id == parent_id).unwrap();
        assert!(parent.parent_span_id.is_none());
    }

    #[test]
    fn export_traces_produces_valid_json() {
        let mut log = EventLog::new();
        let trace_id = "trace-3".to_string();

        let root = log.begin_span(
            "proposal.execute",
            &trace_id,
            None,
            [("proposal_id".to_string(), Value::from("p1"))].into(),
        );
        let child = log.begin_span(
            "action.tool_call",
            &trace_id,
            Some(&root),
            [("tool".to_string(), Value::from("read_file"))].into(),
        );
        log.end_span(&child, SpanStatus::Ok);
        log.end_span(&root, SpanStatus::Ok);

        let json_str = log.export_traces();
        let parsed: Value =
            serde_json::from_str(&json_str).expect("export_traces must produce valid JSON");

        let resource_spans = parsed["resourceSpans"].as_array().unwrap();
        assert_eq!(resource_spans.len(), 1);

        let scope_spans = &resource_spans[0]["scopeSpans"][0]["spans"];
        let spans_arr = scope_spans.as_array().unwrap();
        assert_eq!(spans_arr.len(), 2);

        // Verify OTLP structure
        for span in spans_arr {
            assert!(span.get("traceId").is_some());
            assert!(span.get("spanId").is_some());
            assert!(span.get("name").is_some());
            assert!(span.get("startTimeUnixNano").is_some());
            assert!(span.get("endTimeUnixNano").is_some());
            assert!(span.get("status").is_some());
        }

        // Verify the child has parentSpanId
        let child_span = spans_arr
            .iter()
            .find(|s| s["name"] == "action.tool_call")
            .unwrap();
        assert!(child_span.get("parentSpanId").is_some());
    }

    #[test]
    fn span_status_set_on_error() {
        let mut log = EventLog::new();
        let trace_id = "trace-4".to_string();

        let span_id = log.begin_span("failing.op", &trace_id, None, HashMap::new());
        log.end_span(&span_id, SpanStatus::Error);

        let spans = log.spans();
        assert_eq!(spans[0].status, SpanStatus::Error);
        assert!(spans[0].end_time.is_some());
    }
}