omni-dev 0.29.0

A powerful Git commit message analysis and amendment toolkit
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
//! `~/.omni-dev/voice/<id>/` session directory I/O.
//!
//! Lays out and reads the session directory format from #799:
//!
//! ```text
//! ~/.omni-dev/voice/<session-id>/
//!   meta.yaml          # session config (this issue: last_reflected_event_id + ttl defaults)
//!   transcript.jsonl   # append-only TranscriptEvent stream from `voice transcribe`
//!   events.jsonl       # append-only Event stream from `voice reflect` (and later `voice review`)
//!   reflections.log    # per-reflection summary line (cost, latency, status)
//! ```
//!
//! Shared with #804 (`voice review`), which reads the same `events.jsonl`
//! to produce materialised markdown projections. The session root path is
//! derived from `dirs::home_dir()` by default; the `OMNI_DEV_VOICE_ROOT`
//! environment variable overrides it (intended for tests, not a stable
//! user-facing knob).

use std::fs::{File, OpenOptions};
use std::io::{BufRead, BufReader, BufWriter, Write};
use std::path::{Path, PathBuf};
use std::time::Duration;

use anyhow::{bail, Context, Result};
use serde::{Deserialize, Serialize};

use crate::voice::events::Event;
use crate::voice::{EventId, TranscriptEvent};

/// Filesystem paths under a single session directory.
#[derive(Debug, Clone)]
pub struct SessionPaths {
    /// Session root (`<voice-root>/<id>`).
    pub root: PathBuf,
    /// `meta.yaml` — session config (parsed into [`SessionMeta`]).
    pub meta: PathBuf,
    /// `transcript.jsonl` — `TranscriptEvent` log.
    pub transcript: PathBuf,
    /// `events.jsonl` — reflection [`Event`] log.
    pub events: PathBuf,
    /// `reflections.log` — per-reflection summary lines.
    pub log: PathBuf,
}

impl SessionPaths {
    /// Builds [`SessionPaths`] under `voice_root/<id>` without touching disk.
    #[must_use]
    pub fn under(voice_root: &Path, id: &str) -> Self {
        let root = voice_root.join(id);
        Self {
            meta: root.join("meta.yaml"),
            transcript: root.join("transcript.jsonl"),
            events: root.join("events.jsonl"),
            log: root.join("reflections.log"),
            root,
        }
    }
}

/// Default TTLs per item class (per #799), stored in `meta.yaml` so a
/// session can override them. Serialised as integer seconds.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TtlDefaults {
    /// TTL for `class: todo` items.
    #[serde(with = "ttl_secs")]
    pub todo: Duration,
    /// TTL for `class: research` items.
    #[serde(with = "ttl_secs")]
    pub research: Duration,
    /// TTL for `class: question` items.
    #[serde(with = "ttl_secs")]
    pub question: Duration,
}

impl Default for TtlDefaults {
    fn default() -> Self {
        Self {
            todo: Duration::from_secs(7 * 86_400),
            research: Duration::from_secs(30 * 86_400),
            question: Duration::from_secs(14 * 86_400),
        }
    }
}

mod ttl_secs {
    use serde::{Deserialize, Deserializer, Serializer};
    use std::time::Duration;

    pub fn serialize<S: Serializer>(d: &Duration, s: S) -> Result<S::Ok, S::Error> {
        s.serialize_u64(d.as_secs())
    }

    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Duration, D::Error> {
        let secs = u64::deserialize(d)?;
        Ok(Duration::from_secs(secs))
    }
}

/// Parsed contents of `meta.yaml`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct SessionMeta {
    /// `event_id` of the last `TranscriptEvent::Final` consumed by a
    /// previous `voice reflect` invocation. `None` until the first
    /// reflection completes.
    #[serde(default)]
    pub last_reflected_event_id: Option<EventId>,
    /// TTL defaults applied at projection time (consumed by #804).
    #[serde(default)]
    pub ttl_defaults: TtlDefaults,
}

/// Combination of paths and the parsed meta document.
#[derive(Debug, Clone)]
pub struct Session {
    /// On-disk paths under the session root.
    pub paths: SessionPaths,
    /// Parsed `meta.yaml` contents.
    pub meta: SessionMeta,
}

impl Session {
    /// Reads all `Final` transcript events from `transcript.jsonl` after
    /// `meta.last_reflected_event_id`. Non-`Final` events are skipped —
    /// reflection is driven by committed text only.
    pub fn read_transcript_finals_after(&self) -> Result<Vec<TranscriptEvent>> {
        read_transcript_finals_after(&self.paths.transcript, self.meta.last_reflected_event_id)
    }

    /// Reads `events.jsonl` into a [`Vec<Event>`]. Empty when the file
    /// doesn't exist or contains no events.
    pub fn read_events(&self) -> Result<Vec<Event>> {
        read_events(&self.paths.events)
    }

    /// Appends events to `events.jsonl`.
    pub fn append_events(&self, events: &[Event]) -> Result<()> {
        append_events(&self.paths.events, events)
    }

    /// Updates `meta.last_reflected_event_id` in memory and on disk.
    pub fn set_last_reflected(&mut self, id: EventId) -> Result<()> {
        self.meta.last_reflected_event_id = Some(id);
        write_meta(&self.paths.meta, &self.meta)
    }

    /// Appends a single line to `reflections.log` (no implicit newline).
    pub fn append_log(&self, line: &str) -> Result<()> {
        append_log_line(&self.paths.log, line)
    }
}

/// Resolves the session root: `$OMNI_DEV_VOICE_ROOT` if set, else
/// `~/.omni-dev/voice`.
pub fn voice_root() -> Result<PathBuf> {
    if let Ok(override_root) = std::env::var("OMNI_DEV_VOICE_ROOT") {
        return Ok(PathBuf::from(override_root));
    }
    let home = dirs::home_dir().context(
        "could not determine HOME directory for ~/.omni-dev/voice; \
         set OMNI_DEV_VOICE_ROOT to override",
    )?;
    Ok(home.join(".omni-dev").join("voice"))
}

/// Opens an existing session, or creates an empty one if the directory
/// doesn't exist. Bootstrap is idempotent: re-running against an
/// already-populated session reads the existing `meta.yaml`.
pub fn open_or_create(id: &str) -> Result<Session> {
    let root = voice_root()?;
    open_or_create_under(&root, id)
}

/// Variant of [`open_or_create`] that takes an explicit voice root —
/// useful for tests that drive several sessions under a `tempfile`
/// directory.
pub fn open_or_create_under(voice_root: &Path, id: &str) -> Result<Session> {
    if id.is_empty() {
        bail!("session id cannot be empty");
    }
    if id.contains('/') || id.contains('\\') || id == "." || id == ".." {
        bail!("session id must not contain path separators: {id:?}");
    }
    let paths = SessionPaths::under(voice_root, id);
    std::fs::create_dir_all(&paths.root)
        .with_context(|| format!("creating session directory at {}", paths.root.display()))?;

    // Bootstrap empty files (touch only — don't truncate existing ones).
    for p in [&paths.transcript, &paths.events, &paths.log] {
        if !p.exists() {
            OpenOptions::new()
                .create(true)
                .append(true)
                .open(p)
                .with_context(|| format!("creating {}", p.display()))?;
        }
    }

    let meta = if paths.meta.exists() {
        read_meta(&paths.meta)?
    } else {
        let m = SessionMeta::default();
        write_meta(&paths.meta, &m)?;
        m
    };

    Ok(Session { paths, meta })
}

/// Reads and parses `meta.yaml`.
pub fn read_meta(path: &Path) -> Result<SessionMeta> {
    let body = std::fs::read_to_string(path)
        .with_context(|| format!("reading session meta at {}", path.display()))?;
    serde_yaml::from_str(&body)
        .with_context(|| format!("parsing session meta at {}", path.display()))
}

/// Writes `meta.yaml` atomically (write-temp-then-rename).
pub fn write_meta(path: &Path, meta: &SessionMeta) -> Result<()> {
    let body = serde_yaml::to_string(meta).context("serialising session meta to YAML")?;
    let tmp = path.with_extension("yaml.tmp");
    std::fs::write(&tmp, body.as_bytes())
        .with_context(|| format!("writing temp meta at {}", tmp.display()))?;
    std::fs::rename(&tmp, path)
        .with_context(|| format!("renaming temp meta to {}", path.display()))?;
    Ok(())
}

/// Reads all `TranscriptEvent`s from a JSONL file. Blank lines are
/// skipped; parse errors include the line number.
pub fn read_transcript(path: &Path) -> Result<Vec<TranscriptEvent>> {
    let file =
        File::open(path).with_context(|| format!("opening transcript at {}", path.display()))?;
    let reader = BufReader::new(file);
    let mut events = Vec::new();
    for (idx, line) in reader.lines().enumerate() {
        let line = line.with_context(|| format!("reading {}:{}", path.display(), idx + 1))?;
        if line.trim().is_empty() {
            continue;
        }
        let event: TranscriptEvent = serde_json::from_str(&line)
            .with_context(|| format!("parsing {}:{}", path.display(), idx + 1))?;
        events.push(event);
    }
    Ok(events)
}

/// Reads only `Final` transcript events after the optional marker.
///
/// Uses stream position (not ULID comparison) — finds the marker line
/// and returns Finals strictly after it. Errors if the marker is set
/// but not present in the file.
pub fn read_transcript_finals_after(
    path: &Path,
    after: Option<EventId>,
) -> Result<Vec<TranscriptEvent>> {
    let all = read_transcript(path)?;
    let finals: Vec<TranscriptEvent> = all
        .into_iter()
        .filter(|e| matches!(e, TranscriptEvent::Final { .. }))
        .collect();
    match after {
        None => Ok(finals),
        Some(target) => {
            let pos = finals.iter().position(|e| match e {
                TranscriptEvent::Final { event_id, .. } => *event_id == target,
                _ => false,
            });
            match pos {
                Some(idx) => Ok(finals.into_iter().skip(idx + 1).collect()),
                None => bail!(
                    "last_reflected_event_id {target} not found in transcript at {}; \
                     meta.yaml may be inconsistent with transcript.jsonl",
                    path.display()
                ),
            }
        }
    }
}

/// Reads all reflection [`Event`]s from `events.jsonl`. Returns an empty
/// vec if the file doesn't exist (greenfield session).
pub fn read_events(path: &Path) -> Result<Vec<Event>> {
    if !path.exists() {
        return Ok(Vec::new());
    }
    let file =
        File::open(path).with_context(|| format!("opening events log at {}", path.display()))?;
    let reader = BufReader::new(file);
    let mut events = Vec::new();
    for (idx, line) in reader.lines().enumerate() {
        let line = line.with_context(|| format!("reading {}:{}", path.display(), idx + 1))?;
        if line.trim().is_empty() {
            continue;
        }
        let event: Event = serde_json::from_str(&line)
            .with_context(|| format!("parsing {}:{}", path.display(), idx + 1))?;
        events.push(event);
    }
    Ok(events)
}

/// Appends events as JSONL to `path`. Each event is one line, flushed
/// after the batch. Skips silently when `events` is empty.
pub fn append_events(path: &Path, events: &[Event]) -> Result<()> {
    if events.is_empty() {
        return Ok(());
    }
    let file = OpenOptions::new()
        .create(true)
        .append(true)
        .open(path)
        .with_context(|| format!("opening events log for append at {}", path.display()))?;
    let mut writer = BufWriter::new(file);
    for e in events {
        serde_json::to_writer(&mut writer, e)
            .with_context(|| format!("serialising event to {}", path.display()))?;
        writer
            .write_all(b"\n")
            .with_context(|| format!("appending newline to {}", path.display()))?;
    }
    writer
        .flush()
        .with_context(|| format!("flushing events log at {}", path.display()))?;
    Ok(())
}

/// Appends a single line (with newline) to `reflections.log`. Creates
/// the file if it does not exist.
pub fn append_log_line(path: &Path, line: &str) -> Result<()> {
    let file = OpenOptions::new()
        .create(true)
        .append(true)
        .open(path)
        .with_context(|| format!("opening reflections log at {}", path.display()))?;
    let mut writer = BufWriter::new(file);
    writer
        .write_all(line.as_bytes())
        .with_context(|| format!("writing log line to {}", path.display()))?;
    if !line.ends_with('\n') {
        writer
            .write_all(b"\n")
            .with_context(|| format!("appending newline to {}", path.display()))?;
    }
    writer
        .flush()
        .with_context(|| format!("flushing reflections log at {}", path.display()))?;
    Ok(())
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;
    use crate::voice::events::{
        EventKind, ItemClass, ItemCreate, Provenance, ReflectionId, TranscriptSpan,
    };
    use crate::voice::transcriber::EndpointKind;
    use chrono::TimeZone;
    use tempfile::TempDir;

    fn fixed_ts() -> chrono::DateTime<chrono::Utc> {
        chrono::Utc.with_ymd_and_hms(2026, 1, 1, 0, 0, 0).unwrap()
    }

    fn provenance() -> Provenance {
        Provenance {
            transcript_span: Some(TranscriptSpan {
                start_event_id: ulid::Ulid::from_parts(0, 1),
                end_event_id: ulid::Ulid::from_parts(0, 2),
            }),
            model: Some("m".into()),
            prompt_version: Some("p".into()),
        }
    }

    fn make_event(event_id: u128) -> Event {
        Event {
            event_id: ulid::Ulid::from_parts(0, event_id),
            ts: fixed_ts(),
            reflection_id: ReflectionId::Ulid(ulid::Ulid::from_parts(0, 100)),
            provenance: provenance(),
            kind: EventKind::ItemCreate(ItemCreate {
                item_id: ulid::Ulid::from_parts(0, 500),
                class: ItemClass::Todo,
                text: format!("event {event_id}"),
                priority: None,
                valid_until: None,
                tags: None,
            }),
        }
    }

    fn make_final(event_id: u128, text: &str) -> TranscriptEvent {
        TranscriptEvent::Final {
            event_id: ulid::Ulid::from_parts(0, event_id),
            text: text.to_string(),
            start: Duration::from_millis(0),
            end: Duration::from_millis(100),
            confidence: 0.9,
            words: None,
            speaker: None,
            revisable: false,
        }
    }

    #[test]
    fn open_or_create_bootstraps_an_empty_session() {
        let tmp = TempDir::new().unwrap();
        let session = open_or_create_under(tmp.path(), "s1").unwrap();
        assert!(session.paths.meta.exists());
        assert!(session.paths.transcript.exists());
        assert!(session.paths.events.exists());
        assert!(session.paths.log.exists());
        assert_eq!(session.meta, SessionMeta::default());
    }

    #[test]
    fn open_or_create_is_idempotent() {
        let tmp = TempDir::new().unwrap();
        let s1 = open_or_create_under(tmp.path(), "s1").unwrap();
        let s2 = open_or_create_under(tmp.path(), "s1").unwrap();
        assert_eq!(s1.meta, s2.meta);
    }

    #[test]
    fn open_or_create_preserves_existing_meta() {
        let tmp = TempDir::new().unwrap();
        let mut s = open_or_create_under(tmp.path(), "s1").unwrap();
        s.set_last_reflected(ulid::Ulid::from_parts(0, 42)).unwrap();
        let reopened = open_or_create_under(tmp.path(), "s1").unwrap();
        assert_eq!(
            reopened.meta.last_reflected_event_id,
            Some(ulid::Ulid::from_parts(0, 42))
        );
    }

    #[test]
    fn rejects_session_id_with_path_separator() {
        let tmp = TempDir::new().unwrap();
        assert!(open_or_create_under(tmp.path(), "a/b").is_err());
        assert!(open_or_create_under(tmp.path(), "a\\b").is_err());
        assert!(open_or_create_under(tmp.path(), "..").is_err());
        assert!(open_or_create_under(tmp.path(), ".").is_err());
        assert!(open_or_create_under(tmp.path(), "").is_err());
    }

    #[test]
    fn ttl_defaults_match_799_defaults() {
        let t = TtlDefaults::default();
        assert_eq!(t.todo, Duration::from_secs(7 * 86_400));
        assert_eq!(t.research, Duration::from_secs(30 * 86_400));
        assert_eq!(t.question, Duration::from_secs(14 * 86_400));
    }

    #[test]
    fn meta_yaml_round_trip_preserves_optional_marker() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("meta.yaml");
        let meta = SessionMeta {
            last_reflected_event_id: Some(ulid::Ulid::from_parts(0, 7)),
            ttl_defaults: TtlDefaults::default(),
        };
        write_meta(&path, &meta).unwrap();
        let back = read_meta(&path).unwrap();
        assert_eq!(meta, back);
    }

    #[test]
    fn append_then_read_events_round_trips() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("events.jsonl");
        append_events(&path, &[make_event(1), make_event(2)]).unwrap();
        let back = read_events(&path).unwrap();
        assert_eq!(back.len(), 2);
        assert_eq!(back[0], make_event(1));
        assert_eq!(back[1], make_event(2));
    }

    #[test]
    fn append_events_with_empty_slice_is_noop() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("events.jsonl");
        append_events(&path, &[]).unwrap();
        assert!(!path.exists());
    }

    #[test]
    fn read_events_on_missing_file_returns_empty() {
        let tmp = TempDir::new().unwrap();
        let result = read_events(&tmp.path().join("nothing.jsonl")).unwrap();
        assert!(result.is_empty());
    }

    #[test]
    fn read_transcript_finals_after_filters_partials_and_endpoints() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("transcript.jsonl");
        std::fs::write(
            &path,
            format!(
                "{}\n{}\n{}\n",
                serde_json::to_string(&TranscriptEvent::Partial {
                    text: "ignored".into(),
                    start: Duration::ZERO,
                    end: Duration::from_millis(50),
                    words: None,
                    speaker: None,
                })
                .unwrap(),
                serde_json::to_string(&make_final(1, "first")).unwrap(),
                serde_json::to_string(&TranscriptEvent::Endpoint {
                    at: Duration::from_secs(1),
                    kind: EndpointKind::StreamEnd,
                })
                .unwrap(),
            ),
        )
        .unwrap();
        let finals = read_transcript_finals_after(&path, None).unwrap();
        assert_eq!(finals.len(), 1);
    }

    #[test]
    fn read_transcript_finals_after_skips_through_marker() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("transcript.jsonl");
        let lines = [
            serde_json::to_string(&make_final(1, "a")).unwrap(),
            serde_json::to_string(&make_final(2, "b")).unwrap(),
            serde_json::to_string(&make_final(3, "c")).unwrap(),
        ];
        std::fs::write(&path, lines.join("\n")).unwrap();
        let after_id = ulid::Ulid::from_parts(0, 2);
        let finals = read_transcript_finals_after(&path, Some(after_id)).unwrap();
        assert_eq!(finals.len(), 1);
        match &finals[0] {
            TranscriptEvent::Final { text, .. } => assert_eq!(text, "c"),
            other => panic!("expected Final, got {other:?}"),
        }
    }

    #[test]
    fn read_transcript_finals_after_errors_when_marker_missing() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("transcript.jsonl");
        std::fs::write(
            &path,
            serde_json::to_string(&make_final(1, "a")).unwrap() + "\n",
        )
        .unwrap();
        let err =
            read_transcript_finals_after(&path, Some(ulid::Ulid::from_parts(0, 99))).unwrap_err();
        assert!(
            err.to_string().contains("not found in transcript"),
            "got: {err}"
        );
    }

    #[test]
    fn append_log_line_creates_file_and_adds_newline() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("reflections.log");
        append_log_line(&path, "first entry").unwrap();
        append_log_line(&path, "second entry\n").unwrap();
        let contents = std::fs::read_to_string(&path).unwrap();
        assert_eq!(contents, "first entry\nsecond entry\n");
    }

    #[test]
    fn read_transcript_skips_blank_lines() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("transcript.jsonl");
        std::fs::write(
            &path,
            format!(
                "\n{}\n\n   \n{}\n",
                serde_json::to_string(&make_final(1, "a")).unwrap(),
                serde_json::to_string(&make_final(2, "b")).unwrap(),
            ),
        )
        .unwrap();
        let events = read_transcript(&path).unwrap();
        assert_eq!(events.len(), 2);
    }

    #[test]
    fn read_transcript_reports_parse_failure_with_line_number() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("transcript.jsonl");
        let good = serde_json::to_string(&make_final(1, "ok")).unwrap();
        std::fs::write(&path, format!("{good}\nnot valid json\n")).unwrap();
        let err = read_transcript(&path).unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("parsing") && msg.contains(":2"),
            "error should point at line 2: {msg}"
        );
    }

    #[test]
    fn read_events_skips_blank_lines() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("events.jsonl");
        append_events(&path, &[make_event(1)]).unwrap();
        // Add a blank line after the existing content.
        use std::io::Write as _;
        let mut f = std::fs::OpenOptions::new()
            .append(true)
            .open(&path)
            .unwrap();
        writeln!(f, "\n  ").unwrap();
        drop(f);
        let events = read_events(&path).unwrap();
        assert_eq!(events.len(), 1);
    }

    #[test]
    fn read_events_reports_parse_failure_with_line_number() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("events.jsonl");
        std::fs::write(&path, "not valid json at all\n").unwrap();
        let err = read_events(&path).unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("parsing") && msg.contains(":1"),
            "error should point at line 1: {msg}"
        );
    }

    #[test]
    fn voice_root_respects_override_env_var() {
        // Env mutation is process-wide; restore on exit. No serial guard
        // here because no other test in this module reads/writes the var.
        let original = std::env::var("OMNI_DEV_VOICE_ROOT").ok();
        std::env::set_var("OMNI_DEV_VOICE_ROOT", "/tmp/overridden");
        let root = voice_root().unwrap();
        assert_eq!(root, PathBuf::from("/tmp/overridden"));
        match original {
            Some(v) => std::env::set_var("OMNI_DEV_VOICE_ROOT", v),
            None => std::env::remove_var("OMNI_DEV_VOICE_ROOT"),
        }
    }
}