Skip to main content

vtcode_memory/
event_log.rs

1//! Append-only per-session `ThreadEvent` log plus index and manifest.
2
3use std::collections::{BTreeMap, HashMap, VecDeque};
4use std::fs::File;
5use std::io::{BufRead, Read, Seek, SeekFrom, Write};
6use std::path::{Path, PathBuf};
7use std::sync::atomic::{AtomicBool, Ordering};
8use std::sync::{Arc, Mutex, OnceLock, Weak};
9
10use chrono::Utc;
11use serde::{Deserialize, Serialize};
12use vtcode_commons::VtCodePaths;
13use vtcode_exec_events::{EVENT_SCHEMA_VERSION, ThreadEvent, ThreadItemDetails, VersionedThreadEvent};
14
15use crate::error::SessionStoreError;
16
17/// Sidecar lock file flock-held while a session's event-log handles are open.
18pub(crate) const SESSION_LOCK_FILE: &str = "session.lock";
19use crate::manifest::{ManifestStore, PendingCapRewrite};
20use crate::session_dir;
21
22/// Default maximum number of events retained per session before the oldest
23/// completed turns are evicted.
24pub const DEFAULT_MAX_EVENTS: usize = 10_000;
25
26/// Maximum serialized event bytes retained before an append forces a write.
27/// Turn boundaries and reads still flush immediately.
28const MAX_WRITE_BUFFER_BYTES: usize = 64 * 1024;
29const MAX_EVICTION_GROUNDED_FACTS: usize = 32;
30const MAX_EVICTION_GROUNDED_FACT_BYTES: usize = 512;
31
32/// Callback used to persist a summary of events before they are evicted.
33///
34/// The callback runs after the event bytes have been flushed and decoded, but
35/// before the canonical log is rewritten. A failure leaves the original log
36/// and in-memory index untouched, so retention never silently discards
37/// history.
38pub type EvictionSummaryHook = Arc<dyn Fn(&[ThreadEvent]) -> Result<(), SessionStoreError> + Send + Sync>;
39
40/// Minimal envelope used while rebuilding the turn index.
41///
42/// The index only needs the event discriminator. Deserializing a complete
43/// [`VersionedThreadEvent`] here would allocate every nested tool argument,
44/// output, and thread item even though none of that payload is retained.
45#[derive(Debug, Deserialize)]
46struct VersionedEventKind<'a> {
47    #[serde(rename = "schema_version", borrow)]
48    _schema_version: &'a str,
49    #[serde(borrow)]
50    event: EventKind<'a>,
51}
52
53#[derive(Debug, Deserialize)]
54struct EventKind<'a> {
55    #[serde(rename = "type", borrow)]
56    kind: &'a str,
57}
58
59/// Zero-clone serialization envelope for `ThreadEvent`.
60///
61/// Produces JSON byte-identical to `VersionedThreadEvent` but borrows the
62/// event by reference instead of cloning it. `append` is called for every
63/// runtime event, and `ThreadEvent` can carry large tool outputs / thread
64/// items — cloning just to feed `serde_json::to_string` was pure waste.
65#[derive(Serialize)]
66struct BorrowedVersionedEvent<'a> {
67    schema_version: &'a str,
68    event: &'a ThreadEvent,
69}
70
71/// Turn-lifecycle discriminator extracted from either a `ThreadEvent` (at
72/// append time) or a raw `&str` kind (during scan).  This is the single
73/// representation that both code paths feed into
74/// [`LogState::apply_lifecycle_event`], eliminating a duplicated state machine.
75#[derive(Debug, Clone, Copy, PartialEq, Eq)]
76enum LifecycleKind {
77    ThreadStarted,
78    ThreadCompleted,
79    TurnStarted,
80    TurnCompleted,
81    TurnFailed,
82    Other,
83}
84
85impl LifecycleKind {
86    /// Discriminate from a runtime `ThreadEvent` at append time.
87    #[inline]
88    fn from_event(event: &ThreadEvent) -> Self {
89        match event {
90            ThreadEvent::ThreadStarted(_) => Self::ThreadStarted,
91            ThreadEvent::ThreadCompleted(_) => Self::ThreadCompleted,
92            ThreadEvent::TurnStarted(_) => Self::TurnStarted,
93            ThreadEvent::TurnCompleted(_) => Self::TurnCompleted,
94            ThreadEvent::TurnFailed(_) => Self::TurnFailed,
95            _ => Self::Other,
96        }
97    }
98
99    /// Discriminate from a raw event-type string at scan time.
100    #[inline]
101    fn from_kind(kind: &str) -> Self {
102        match kind {
103            "thread.started" => Self::ThreadStarted,
104            "thread.completed" => Self::ThreadCompleted,
105            "turn.started" => Self::TurnStarted,
106            "turn.completed" => Self::TurnCompleted,
107            "turn.failed" => Self::TurnFailed,
108            _ => Self::Other,
109        }
110    }
111}
112
113/// In-memory state protected by a mutex (cheap; appends are infrequent relative
114/// to model inference).
115struct LogState {
116    manifest: SessionManifest,
117    index: TurnIndex,
118    /// Whether we are currently inside a turn (between TurnStarted and
119    /// TurnCompleted/TurnFailed). Used to update the last index entry's
120    /// offsets as intermediate events arrive.
121    in_turn: bool,
122    /// Running byte offset of the next append. Avoids a `stat` syscall per
123    /// event (the previous implementation re-statted the file twice on every
124    /// `append`); initialized from the file length on `open`.
125    next_offset: u64,
126    /// Buffered pending writes to batch syscalls. Events are appended here
127    /// and flushed to disk at turn boundaries or before read operations.
128    write_buf: Vec<u8>,
129}
130
131#[derive(Debug, Clone, Copy)]
132struct CapEvictionPlan {
133    truncate_offset: u64,
134    evicted_event_count: u64,
135    evicted_turn_count: usize,
136}
137
138impl LogState {
139    fn new(session_id: &str) -> Self {
140        Self {
141            manifest: SessionManifest::new(session_id),
142            index: TurnIndex::default(),
143            in_turn: false,
144            next_offset: 0,
145            write_buf: Vec::with_capacity(65536),
146        }
147    }
148
149    /// Serialize `event` directly into the reusable write buffer with rollback
150    /// on failure.
151    ///
152    /// This encapsulates the invariant that `write_buf` never contains a
153    /// partial JSON document: if `serde_json::to_writer` fails mid-write the
154    /// buffer is truncated back to its pre-serialization boundary.  Returns
155    /// the `(start, end)` byte offsets of the serialized event so the caller
156    /// can feed them to [`Self::apply_lifecycle_event`].
157    fn serialize_event(&mut self, event: &ThreadEvent) -> Result<(u64, u64), SessionStoreError> {
158        let start = self.next_offset;
159        let buf_len_before = self.write_buf.len();
160        if let Err(err) = serde_json::to_writer(
161            &mut self.write_buf,
162            &BorrowedVersionedEvent { schema_version: EVENT_SCHEMA_VERSION, event },
163        ) {
164            self.write_buf.truncate(buf_len_before);
165            return Err(err.into());
166        }
167        self.write_buf.push(b'\n');
168        let written = self.write_buf.len() - buf_len_before;
169        let end = start + written as u64;
170        self.next_offset = end;
171        Ok((start, end))
172    }
173
174    /// Update the in-memory turn index and manifest counters for a single
175    /// event.
176    ///
177    /// This is the single implementation of the turn-lifecycle state machine;
178    /// both the append path (via [`LifecycleKind::from_event`]) and the scan
179    /// path (via [`LifecycleKind::from_kind`]) route through here, eliminating
180    /// a previously duplicated match block.
181    ///
182    /// Returns `true` when the event closes a turn boundary
183    /// (`TurnCompleted` / `TurnFailed`) so the caller can persist metadata
184    /// at the appropriate time (append persists immediately; scan persists
185    /// once after the full scan).
186    fn apply_lifecycle_event(&mut self, kind: LifecycleKind, start: u64, end: u64) -> bool {
187        let is_boundary = match kind {
188            LifecycleKind::ThreadStarted => {
189                self.manifest.status = "active".to_string();
190                false
191            }
192            LifecycleKind::ThreadCompleted => {
193                self.manifest.status = "completed".to_string();
194                true
195            }
196            LifecycleKind::TurnStarted => {
197                self.manifest.status = "active".to_string();
198                self.in_turn = true;
199                let n = self.manifest.turn_count + 1;
200                self.index.entries.push_back(TurnIndexEntry {
201                    turn_number: n,
202                    start_offset: start,
203                    end_offset: end,
204                    event_count: 1,
205                    ts: now_rfc3339(),
206                });
207                false
208            }
209            LifecycleKind::TurnCompleted | LifecycleKind::TurnFailed => {
210                if self.in_turn {
211                    if let Some(entry) = self.index.entries.back_mut() {
212                        entry.end_offset = end;
213                        entry.event_count += 1;
214                        // `turn_number` remains monotonic when older completed
215                        // turns have been evicted. The manifest is the source
216                        // for the next ordinal, so never replace it with the
217                        // retained index length.
218                        self.manifest.turn_count = self.manifest.turn_count.max(entry.turn_number);
219                    }
220                    self.in_turn = false;
221                }
222                true
223            }
224            LifecycleKind::Other => {
225                if self.in_turn
226                    && let Some(entry) = self.index.entries.back_mut()
227                {
228                    entry.end_offset = end;
229                    entry.event_count += 1;
230                }
231                false
232            }
233        };
234        // Persist the open-turn marker alongside the manifest. The marker is
235        // deliberately optional for backwards compatibility: an older
236        // manifest without it forces a scan on reopen so the state can be
237        // reconstructed from the canonical event log.
238        self.manifest.in_turn = Some(self.in_turn);
239        is_boundary
240    }
241
242    /// Plan a cap-enforcement eviction: pop the oldest completed turns from
243    /// the index until `event_count` is within `max_events`.
244    ///
245    /// Returns the byte offset at which the file should be rewritten and the
246    /// counts needed to apply the eviction after successful I/O. Returns
247    /// `None` when no eviction is needed.
248    fn plan_cap_eviction(&self, max_events: usize) -> Option<CapEvictionPlan> {
249        if max_events == 0 || self.manifest.event_count <= max_events as u64 {
250            return None;
251        }
252        let mut evicted_event_count = 0u64;
253        let mut truncate_offset = 0u64;
254        let mut evicted_turn_count = 0;
255        for (entry_index, oldest) in self.index.entries.iter().enumerate() {
256            // Never evict the active turn. Its entry has a provisional end
257            // offset and will be closed by a later completion/failure event;
258            // removing it here would make that event unindexed and lose the
259            // in-flight turn from reconstruction. If the completed history
260            // alone cannot bring the log under the cap, retain the active
261            // turn until it reaches a terminal boundary.
262            if self.in_turn && entry_index + 1 == self.index.entries.len() {
263                break;
264            }
265            if self.manifest.event_count.saturating_sub(evicted_event_count) <= max_events as u64 {
266                break;
267            }
268            truncate_offset = oldest.end_offset;
269            evicted_event_count += oldest.event_count;
270            evicted_turn_count += 1;
271        }
272        if truncate_offset == 0 || evicted_turn_count == 0 {
273            None
274        } else {
275            Some(CapEvictionPlan {
276                truncate_offset,
277                evicted_event_count,
278                evicted_turn_count,
279            })
280        }
281    }
282
283    fn apply_cap_eviction(&mut self, plan: CapEvictionPlan, next_offset: u64) {
284        for _ in 0..plan.evicted_turn_count {
285            let _ = self.index.entries.pop_front();
286        }
287        for entry in &mut self.index.entries {
288            entry.start_offset = entry.start_offset.saturating_sub(plan.truncate_offset);
289            entry.end_offset = entry.end_offset.saturating_sub(plan.truncate_offset);
290        }
291        self.next_offset = next_offset;
292        self.manifest.event_count = self.manifest.event_count.saturating_sub(plan.evicted_event_count);
293        self.manifest.retained_turn_base = Some(self.retained_turn_base_after_eviction(0));
294    }
295
296    fn retained_turn_base_after_eviction(&self, evicted_turn_count: usize) -> u64 {
297        self.index
298            .entries
299            .get(evicted_turn_count)
300            .map(|entry| entry.turn_number)
301            .or_else(|| self.manifest.turn_count.checked_add(1))
302            .unwrap_or(1)
303            .max(1)
304    }
305}
306
307/// State and file handle shared by every owner of one session in this process.
308///
309/// A keyed operation lock alone is insufficient: two independently opened
310/// handles could still carry stale turn counters and overwrite each other's
311/// metadata after taking the lock. Sharing the mutable state and append file
312/// makes the lock a true session boundary while preserving the value-type
313/// `SessionEventLog` API.
314struct SessionShared {
315    file: Mutex<Option<File>>,
316    state: Mutex<LogState>,
317    eviction_lock: Mutex<()>,
318    initialized: AtomicBool,
319    /// Exclusive flock on the session's `session.lock`, held for as long as
320    /// any handle to this session exists. Retention reads it as a liveness
321    /// signal so an open-but-idle session is never marked or evicted.
322    liveness_lock: Option<File>,
323}
324
325/// Return the process-wide shared state for one session's canonical event file.
326///
327/// The weak registry avoids retaining closed sessions forever while still
328/// making repeated `open` calls converge on one file handle and turn state.
329fn shared_session(events_path: &Path, session_id: &str) -> Result<Arc<SessionShared>, SessionStoreError> {
330    static SESSION_SHARED: OnceLock<Mutex<HashMap<PathBuf, Weak<SessionShared>>>> = OnceLock::new();
331
332    let key = events_path
333        .parent()
334        .and_then(|parent| vtcode_commons::paths::canonicalize(parent).ok())
335        .and_then(|parent| events_path.file_name().map(|name| parent.join(name)))
336        .unwrap_or_else(|| events_path.to_path_buf());
337    let registry = SESSION_SHARED.get_or_init(|| Mutex::new(HashMap::new()));
338    let mut shared_by_path = match registry.lock() {
339        Ok(locks) => locks,
340        Err(poisoned) => poisoned.into_inner(),
341    };
342    // Do not retain dead weak entries for every session ever opened by a
343    // long-running process. The registry is only an in-process coordination
344    // aid, so removing entries with no live owners is safe.
345    shared_by_path.retain(|_, shared| shared.strong_count() > 0);
346    if let Some(shared) = shared_by_path.get(&key).and_then(Weak::upgrade) {
347        return Ok(shared);
348    }
349
350    let file = VtCodePaths::open_private_append_file(events_path)
351        .map_err(|error| SessionStoreError::io(events_path.to_path_buf(), std::io::Error::other(error)))?;
352    let shared = Arc::new(SessionShared {
353        file: Mutex::new(Some(file)),
354        state: Mutex::new(LogState::new(session_id)),
355        eviction_lock: Mutex::new(()),
356        initialized: AtomicBool::new(false),
357        liveness_lock: acquire_liveness_lock(events_path),
358    });
359    shared_by_path.insert(key, Arc::downgrade(&shared));
360    Ok(shared)
361}
362
363/// Best-effort exclusive flock on the session's `session.lock`.
364///
365/// The lock is the liveness signal retention reads (`session_dir_is_live`): a
366/// held lock means a live process still has the session open. The crate has
367/// no logging surface and this is an advisory signal, not persistence, so a
368/// failure to create/open/lock degrades to unlocked (previous retention
369/// behavior) instead of failing the session open or swallowing a persistence
370/// error. The fd is released automatically when the shared handle drops.
371fn acquire_liveness_lock(events_path: &Path) -> Option<File> {
372    let dir = events_path.parent()?;
373    let lock_path = dir.join(SESSION_LOCK_FILE);
374    VtCodePaths::write_private_file_atomic_if_absent(&lock_path, b"").ok()?;
375    let file = std::fs::OpenOptions::new().read(true).write(true).open(&lock_path).ok()?;
376    match file.try_lock() {
377        Ok(()) => Some(file),
378        Err(_) => None,
379    }
380}
381
382/// Canonical append-only event log for a single session.
383///
384/// All session history is reconstructable from this log. Live conversation
385/// state is never read back into context from here; the log is only consumed
386/// for revert, compaction, analytics, and long-term-learning queries.
387pub struct SessionEventLog {
388    events_path: PathBuf,
389    manifest_store: ManifestStore,
390    shared: Arc<SessionShared>,
391    max_events: usize,
392    eviction_summary_hook: EvictionSummaryHook,
393}
394
395impl SessionEventLog {
396    /// Open the log for `session_id`, creating the session directory tree and
397    /// rebuilding the index from `events.jsonl` if it already exists.
398    pub(crate) fn open(workspace: &Path, session_id: &str, max_events: usize) -> Result<Self, SessionStoreError> {
399        let dir = session_dir(workspace, session_id);
400        let hook = default_eviction_summary_hook(dir.join(crate::DERIVED_DIR), session_id.to_string());
401        Self::open_with_eviction_summary(workspace, session_id, max_events, hook)
402    }
403
404    /// Open a log with an explicit eviction-summary callback.
405    ///
406    /// This is useful for hosts that keep derived memory in another store and
407    /// for deterministic failure-path tests. The callback must persist its
408    /// summary before returning `Ok(())`.
409    pub fn open_with_eviction_summary(
410        workspace: &Path,
411        session_id: &str,
412        max_events: usize,
413        eviction_summary_hook: EvictionSummaryHook,
414    ) -> Result<Self, SessionStoreError> {
415        let dir = session_dir(workspace, session_id);
416        crate::ensure_private_directory(&crate::sessions_root(workspace))?;
417        crate::ensure_private_directory(&dir)?;
418        crate::ensure_private_directory(&dir.join(crate::DERIVED_DIR))?;
419        crate::ensure_private_directory(&dir.join("index"))?;
420        let events_path = dir.join("events.jsonl");
421        let manifest_store = ManifestStore::new(dir.clone());
422        let pending_rewrite = manifest_store.load_pending_cap_rewrite()?;
423        let shared = shared_session(&events_path, session_id)?;
424        let log = Self {
425            events_path: events_path.clone(),
426            manifest_store,
427            shared,
428            max_events,
429            eviction_summary_hook,
430        };
431        let _eviction_guard = log.shared.eviction_lock.lock().map_err(poison)?;
432        // Try the fast path: read the persisted manifest + index and skip
433        // the O(n) scan when they are present and consistent.
434        if !log.shared.initialized.load(Ordering::Acquire) {
435            let manifest_opt = log.manifest_store.load_manifest()?;
436            let index_opt = log.manifest_store.load_turn_index()?;
437            let file_len = log.event_file_metadata_len()?;
438            let pending_rewrite_matches_file = pending_rewrite.as_ref().is_some_and(|pending| {
439                pending.new_file_len == file_len && pending.new_file_len < pending.previous_file_len
440            });
441            match (&manifest_opt, &index_opt) {
442                (Some(manifest), Some(index))
443                    if !pending_rewrite_matches_file
444                        && manifest.in_turn.is_some()
445                        && manifest.persisted_file_len == Some(file_len)
446                        && index.is_valid_for_file(file_len)
447                        && index.is_consistent_with_manifest(manifest) =>
448                {
449                    let mut st = log.shared.state.lock().map_err(poison)?;
450                    st.in_turn = manifest.in_turn.unwrap_or(false);
451                    st.manifest = manifest.clone();
452                    st.index = index.clone();
453                    st.next_offset = file_len;
454                }
455                _ => {
456                    let scan_turn_base = infer_scan_turn_base(
457                        manifest_opt.as_ref(),
458                        index_opt.as_ref(),
459                        pending_rewrite.as_ref().filter(|_| pending_rewrite_matches_file),
460                        file_len,
461                    );
462                    {
463                        let mut st = log.shared.state.lock().map_err(poison)?;
464                        if let Some(previous) = manifest_opt.as_ref() {
465                            st.manifest = previous.clone();
466                        }
467                        // The canonical event file is authoritative after any
468                        // stale/corrupt metadata. Preserve the ordinal of the
469                        // first retained turn while rebuilding all counters.
470                        st.manifest.turn_count = scan_turn_base.saturating_sub(1);
471                        st.manifest.event_count = 0;
472                        st.manifest.status = "active".to_string();
473                        st.manifest.in_turn = Some(false);
474                        st.manifest.retained_turn_base = Some(scan_turn_base);
475                        st.index = TurnIndex::default();
476                        st.in_turn = false;
477                    }
478                    log.scan()?;
479                    let mut st = log.shared.state.lock().map_err(poison)?;
480                    st.next_offset = file_len;
481                    log.persist_meta_locked(&mut st)?;
482                }
483            }
484            if pending_rewrite.is_some() {
485                // A marker whose file length did not match either side of the
486                // rewrite is stale, while a matching marker has now been
487                // incorporated into the repaired metadata. In both cases it
488                // is safe to remove it after the open path has persisted the
489                // authoritative state.
490                log.manifest_store.clear_pending_cap_rewrite()?;
491            }
492            log.shared.initialized.store(true, Ordering::Release);
493        }
494        drop(_eviction_guard);
495        Ok(log)
496    }
497
498    /// Append an event to the log and update the in-memory index/manifest.
499    pub fn append(&self, event: &ThreadEvent) -> Result<(), SessionStoreError> {
500        let _eviction_guard = self.shared.eviction_lock.lock().map_err(poison)?;
501        let mut st = self.shared.state.lock().map_err(poison)?;
502
503        // Serialize into the write buffer with rollback on failure — the
504        // invariant that `write_buf` never contains partial JSON is
505        // encapsulated in `serialize_event`.
506        let (start, end) = st.serialize_event(event)?;
507
508        st.manifest.event_count += 1;
509        st.manifest.updated_at = now_rfc3339();
510
511        // Route through the single turn-lifecycle state machine.  When the
512        // event closes a turn, persist metadata immediately so a reopen
513        // after a mid-turn crash sees a consistent index.
514        let is_turn_boundary = st.apply_lifecycle_event(LifecycleKind::from_event(event), start, end);
515        if is_turn_boundary {
516            self.persist_meta_locked(&mut st)?;
517        }
518
519        if st.write_buf.len() >= MAX_WRITE_BUFFER_BYTES {
520            // Persist metadata with the bounded byte flush so a reopen after
521            // a mid-turn crash does not trust an index that predates these
522            // already-written events.
523            self.persist_meta_locked(&mut st)?;
524        }
525        drop(st);
526        self.enforce_event_cap()
527    }
528
529    /// Enforce the per-session event cap by evicting the oldest completed
530    /// turns when the log exceeds [`Self::max_events`]. Returns `Ok(())` even
531    /// when no truncation is needed or the cap is disabled (`max_events == 0`).
532    fn enforce_event_cap(&self) -> Result<(), SessionStoreError> {
533        let mut st = self.shared.state.lock().map_err(poison)?;
534
535        // `plan_cap_eviction` encapsulates the index arithmetic and returns
536        // `None` when the cap is disabled or not yet exceeded.
537        let Some(plan) = st.plan_cap_eviction(self.max_events) else {
538            return Ok(());
539        };
540
541        // Keep ordinary appends in memory until a turn boundary or an
542        // explicit read. Cap enforcement is the one append-time path that
543        // needs the complete on-disk file before rewriting it.
544        self.flush_write_buf_locked(&mut st)?;
545
546        let (evicted, remaining, previous_file_len) = {
547            let mut file_slot = self.shared.file.lock().map_err(poison)?;
548            let file = file_slot.as_mut().ok_or_else(|| self.event_file_unavailable())?;
549            let file_len = file
550                .metadata()
551                .map_err(|error| SessionStoreError::io(&self.events_path, error))?
552                .len();
553            if plan.truncate_offset > file_len {
554                return Err(SessionStoreError::io(
555                    &self.events_path,
556                    std::io::Error::new(std::io::ErrorKind::InvalidData, "cap offset exceeds event log length"),
557                ));
558            }
559            file.seek(SeekFrom::Start(0))
560                .map_err(|e| SessionStoreError::io(&self.events_path, e))?;
561            let mut evicted = vec![
562                0u8;
563                usize::try_from(plan.truncate_offset).map_err(|error| {
564                    SessionStoreError::io(
565                        &self.events_path,
566                        std::io::Error::new(std::io::ErrorKind::InvalidData, error),
567                    )
568                })?
569            ];
570            file.read_exact(&mut evicted)
571                .map_err(|e| SessionStoreError::io(&self.events_path, e))?;
572            file.seek(SeekFrom::Start(plan.truncate_offset))
573                .map_err(|e| SessionStoreError::io(&self.events_path, e))?;
574            let mut remaining = Vec::new();
575            file.read_to_end(&mut remaining)
576                .map_err(|e| SessionStoreError::io(&self.events_path, e))?;
577            (evicted, remaining, file_len)
578        };
579        let retained_turn_base = st.retained_turn_base_after_eviction(plan.evicted_turn_count);
580        drop(st);
581
582        // The turn index counts only records inside indexed turns. The bytes
583        // removed by a cap rewrite may also contain valid session-level
584        // records (for example `thread.started`) before the first turn, so
585        // reconcile the manifest against the actual persisted prefix rather
586        // than the turn-only estimate from `plan_cap_eviction`.
587        let mut plan = plan;
588        plan.evicted_event_count = count_persisted_event_records(&evicted);
589        let evicted_events = decode_events(&evicted);
590        (self.eviction_summary_hook)(&evicted_events)?;
591
592        let new_file_len = u64::try_from(remaining.len()).map_err(|error| {
593            SessionStoreError::io(&self.events_path, std::io::Error::new(std::io::ErrorKind::InvalidData, error))
594        })?;
595        self.manifest_store.write_pending_cap_rewrite(&PendingCapRewrite {
596            previous_file_len,
597            new_file_len,
598            retained_turn_base,
599        })?;
600        let next_offset = self.replace_event_file_contents(&remaining)?;
601        let mut st = self.shared.state.lock().map_err(poison)?;
602        st.apply_cap_eviction(plan, next_offset);
603        // The rewrite changed byte offsets and retained counts; persist the
604        // derived metadata before exposing the append as successful.
605        self.persist_meta_locked(&mut st)?;
606        self.manifest_store.clear_pending_cap_rewrite()?;
607        Ok(())
608    }
609
610    /// Reconstruct every event belonging to `turn`.
611    pub(crate) fn reconstruct_turn(&self, turn: u64) -> Result<Vec<ThreadEvent>, SessionStoreError> {
612        // Keep the index snapshot and byte-range read together with cap
613        // rewriting. Otherwise an eviction can replace the file between these
614        // steps and leave the snapshot offsets pointing into unrelated events.
615        let _eviction_guard = self.shared.eviction_lock.lock().map_err(poison)?;
616        let entry = {
617            let st = self.shared.state.lock().map_err(poison)?;
618            st.index
619                .entries
620                .iter()
621                .find(|e| e.turn_number == turn)
622                .cloned()
623                .ok_or(SessionStoreError::TurnNotFound { session: st.manifest.session_id.clone(), turn })?
624        };
625        {
626            let mut st = self.shared.state.lock().map_err(poison)?;
627            self.flush_write_buf_locked(&mut st)?;
628        }
629        let buf = {
630            let mut file_slot = self.shared.file.lock().map_err(poison)?;
631            let file = file_slot.as_mut().ok_or_else(|| self.event_file_unavailable())?;
632            file.seek(SeekFrom::Start(entry.start_offset))
633                .map_err(|e| SessionStoreError::io(&self.events_path, e))?;
634            let len = usize::try_from(entry.end_offset.checked_sub(entry.start_offset).ok_or_else(|| {
635                SessionStoreError::io(
636                    &self.events_path,
637                    std::io::Error::new(std::io::ErrorKind::InvalidData, "turn index offsets are out of order"),
638                )
639            })?)
640            .map_err(|error| {
641                SessionStoreError::io(&self.events_path, std::io::Error::new(std::io::ErrorKind::InvalidData, error))
642            })?;
643            let mut buf = vec![0u8; len];
644            file.read_exact(&mut buf)
645                .map_err(|e| SessionStoreError::io(&self.events_path, e))?;
646            buf
647        };
648        let text = String::from_utf8_lossy(&buf);
649        let mut events = Vec::new();
650        for line in text.lines() {
651            let line = line.trim();
652            if line.is_empty() {
653                continue;
654            }
655            // The index scan only validates the event envelope (plus the
656            // lifecycle shape) so it can rebuild cheaply. A line accepted by
657            // the scan can therefore still fail full decoding here; skip it
658            // instead of failing the whole reconstruction (revert, compaction,
659            // and analytics must not break on a single malformed record).
660            let v: VersionedThreadEvent = match serde_json::from_str(line) {
661                Ok(v) => v,
662                Err(_) => continue,
663            };
664            events.push(v.into_event());
665        }
666        Ok(events)
667    }
668
669    /// Number of turns recorded.
670    #[must_use]
671    pub(crate) fn turn_count(&self) -> u64 {
672        self.shared.state.lock().map_err(poison).map_or(0, |s| s.manifest.turn_count)
673    }
674
675    /// Number of events recorded.
676    #[must_use]
677    pub fn event_count(&self) -> u64 {
678        self.shared.state.lock().map_err(poison).map_or(0, |s| s.manifest.event_count)
679    }
680
681    /// Flush pending event bytes and metadata to the session store.
682    /// Visit one consistent retained range, including records outside turns.
683    /// Reads are streamed while cap rewrites and appends are excluded.
684    pub fn visit_snapshot<F>(&self, mut visitor: F) -> Result<SessionManifest, SessionStoreError>
685    where
686        F: FnMut(u64, &[u8]),
687    {
688        use std::io::{BufRead, BufReader};
689        let _eviction_guard = self.shared.eviction_lock.lock().map_err(poison)?;
690        let mut st = self.shared.state.lock().map_err(poison)?;
691        self.persist_meta_locked(&mut st)?;
692        let mut file_slot = self.shared.file.lock().map_err(poison)?;
693        let file = file_slot.as_mut().ok_or_else(|| self.event_file_unavailable())?;
694        file.seek(SeekFrom::Start(0))
695            .map_err(|e| SessionStoreError::io(&self.events_path, e))?;
696        let mut reader = BufReader::new(file.take(st.next_offset));
697        let mut offset = 0;
698        let mut line = Vec::new();
699        loop {
700            line.clear();
701            let length = reader
702                .read_until(b'\n', &mut line)
703                .map_err(|e| SessionStoreError::io(&self.events_path, e))?;
704            if length == 0 {
705                break;
706            }
707            visitor(offset, &line);
708            offset += length as u64;
709        }
710        Ok(st.manifest.clone())
711    }
712
713    /// Flush pending event bytes and metadata to the session store.
714    pub fn flush(&self) -> Result<(), SessionStoreError> {
715        let _eviction_guard = self.shared.eviction_lock.lock().map_err(poison)?;
716        let mut st = self.shared.state.lock().map_err(poison)?;
717        self.persist_meta_locked(&mut st)
718    }
719
720    /// Snapshot of the session manifest.
721    #[must_use]
722    pub fn manifest(&self) -> SessionManifest {
723        self.shared
724            .state
725            .lock()
726            .map_err(poison)
727            .map(|s| s.manifest.clone())
728            .unwrap_or_else(|_| SessionManifest::new(""))
729    }
730
731    /// Snapshot of the turn index.
732    #[must_use]
733    pub fn turn_index(&self) -> TurnIndex {
734        self.shared
735            .state
736            .lock()
737            .map_err(poison)
738            .map(|s| s.index.clone())
739            .unwrap_or_default()
740    }
741
742    /// Flush metadata for callers that explicitly close a log handle.
743    ///
744    /// Terminal status is intentionally controlled only by a persisted
745    /// `thread.completed` event. This method does not synthesize lifecycle
746    /// state for callers that merely release a store handle.
747    pub(crate) fn complete(&self) -> Result<(), SessionStoreError> {
748        let _eviction_guard = self.shared.eviction_lock.lock().map_err(poison)?;
749        let mut st = self.shared.state.lock().map_err(poison)?;
750        st.manifest.updated_at = now_rfc3339();
751        self.persist_meta_locked(&mut st)
752    }
753
754    /// Rebuild index + manifest by scanning `events.jsonl` (authoritative).
755    ///
756    /// Reads the file line-by-line via `BufReader` to avoid loading the entire
757    /// log into memory. Long-lived sessions can otherwise produce multi-megabyte
758    /// logs that spike memory on every reopen.
759    fn scan(&self) -> Result<(), SessionStoreError> {
760        let mut st = self.shared.state.lock().map_err(poison)?;
761        let file = self
762            .shared
763            .file
764            .lock()
765            .map_err(poison)?
766            .as_ref()
767            .ok_or_else(|| self.event_file_unavailable())?
768            .try_clone()
769            .map_err(|e| SessionStoreError::io(&self.events_path, e))?;
770        let mut reader = std::io::BufReader::new(file);
771        reader
772            .seek(SeekFrom::Start(0))
773            .map_err(|e| SessionStoreError::io(&self.events_path, e))?;
774        let mut buf = Vec::new();
775        let mut pos = 0u64;
776        let mut first_ts: Option<String> = None;
777        loop {
778            buf.clear();
779            let n = reader
780                .read_until(b'\n', &mut buf)
781                .map_err(|e| SessionStoreError::io(&self.events_path, e))?;
782            if n == 0 {
783                break;
784            }
785            let line_end = pos + n as u64;
786            let trimmed = std::str::from_utf8(&buf).unwrap_or("").trim();
787            if !trimmed.is_empty()
788                && let Ok(v) = serde_json::from_str::<VersionedEventKind<'_>>(trimmed)
789            {
790                let kind = v.event.kind;
791                if requires_full_lifecycle_validation(kind) && !valid_lifecycle_payload(kind, trimmed) {
792                    pos = line_end;
793                    continue;
794                }
795                st.manifest.event_count += 1;
796                // `thread.started` is not part of the turn lifecycle — it
797                // only seeds `created_at` on the first occurrence.
798                if kind == "thread.started" && first_ts.is_none() {
799                    first_ts = Some(now_rfc3339());
800                }
801                // Route turn-lifecycle events through the same state machine
802                // as `append`, eliminating a previously duplicated match block.
803                st.apply_lifecycle_event(LifecycleKind::from_kind(kind), pos, line_end);
804            }
805            pos = line_end;
806        }
807        // Keep the open-turn state reconstructed from the canonical event log.
808        // This lets a reopened session continue a turn that was flushed before
809        // its completion event was written.
810        st.manifest.in_turn = Some(st.in_turn);
811        if let Some(ts) = first_ts
812            && st.manifest.created_at.is_empty()
813        {
814            st.manifest.created_at = ts;
815        }
816        Ok(())
817    }
818
819    fn persist_meta_locked(&self, st: &mut LogState) -> Result<(), SessionStoreError> {
820        self.flush_write_buf_locked(st)?;
821        // The manifest is only eligible for the fast reopen path when it
822        // describes the complete on-disk event file. Drop intentionally
823        // flushes bytes without metadata, so a length mismatch safely forces
824        // the authoritative scan on the next open.
825        st.manifest.persisted_file_len = Some(st.next_offset);
826        // Publish the derived index first. If a process stops between these
827        // two atomic renames, the older manifest still carries a stale file
828        // length and forces a scan instead of allowing the new manifest to
829        // pair with an older, apparently valid index.
830        self.manifest_store.write_turn_index(&st.index)?;
831        self.manifest_store.write_manifest(&st.manifest)?;
832        Ok(())
833    }
834
835    /// Flush the in-memory write buffer to the underlying file.
836    fn flush_write_buf_locked(&self, st: &mut LogState) -> Result<(), SessionStoreError> {
837        if st.write_buf.is_empty() {
838            return Ok(());
839        }
840        let mut file_slot = self.shared.file.lock().map_err(poison)?;
841        let file = file_slot.as_mut().ok_or_else(|| self.event_file_unavailable())?;
842        let previous_len = file.metadata().map_err(|e| SessionStoreError::io(&self.events_path, e))?.len();
843        if let Err(error) = file.write_all(&st.write_buf) {
844            if file.set_len(previous_len).is_err() {
845                st.write_buf.clear();
846            }
847            return Err(SessionStoreError::io(&self.events_path, error));
848        }
849        if let Err(error) = file.sync_data() {
850            st.write_buf.clear();
851            return Err(SessionStoreError::io(&self.events_path, error));
852        }
853        st.write_buf.clear();
854        Ok(())
855    }
856
857    fn event_file_metadata_len(&self) -> Result<u64, SessionStoreError> {
858        let file_slot = self.shared.file.lock().map_err(poison)?;
859        file_slot
860            .as_ref()
861            .ok_or_else(|| self.event_file_unavailable())?
862            .metadata()
863            .map(|metadata| metadata.len())
864            .map_err(|error| SessionStoreError::io(&self.events_path, error))
865    }
866
867    fn open_event_file(&self) -> Result<File, SessionStoreError> {
868        VtCodePaths::open_private_append_file(&self.events_path)
869            .map_err(|error| SessionStoreError::io(&self.events_path, std::io::Error::other(error)))
870    }
871
872    fn replace_event_file_contents(&self, contents: &[u8]) -> Result<u64, SessionStoreError> {
873        let old_file = {
874            let mut file_slot = self.shared.file.lock().map_err(poison)?;
875            file_slot.take().ok_or_else(|| self.event_file_unavailable())?
876        };
877        drop(old_file);
878
879        if let Err(error) = VtCodePaths::write_private_file_atomic(&self.events_path, contents)
880            .map_err(|error| SessionStoreError::io(&self.events_path, std::io::Error::other(error)))
881        {
882            let restored = self.open_event_file();
883            if let Ok(file) = restored {
884                let mut file_slot = self.shared.file.lock().map_err(poison)?;
885                *file_slot = Some(file);
886                return Err(error);
887            }
888            return Err(SessionStoreError::io(
889                &self.events_path,
890                std::io::Error::other(format!("{error}; failed to restore event log handle")),
891            ));
892        }
893
894        let replacement = self.open_event_file()?;
895        let next_offset = replacement
896            .metadata()
897            .map_err(|error| SessionStoreError::io(&self.events_path, error))?
898            .len();
899        let mut file_slot = self.shared.file.lock().map_err(poison)?;
900        *file_slot = Some(replacement);
901        Ok(next_offset)
902    }
903
904    fn event_file_unavailable(&self) -> SessionStoreError {
905        SessionStoreError::io(&self.events_path, std::io::Error::other("event log file is unavailable"))
906    }
907}
908
909/// Recover the ordinal of the first retained turn when metadata is stale.
910///
911/// A cap rewrite atomically replaces the event file before it publishes the
912/// shortened index and manifest. If the process crashes in that interval,
913/// the old index still records the pre-rewrite offsets. The difference between
914/// its persisted length and the current file length is exactly the removed
915/// prefix, so the first old index entry at that boundary supplies the retained
916/// turn base. Other stale metadata falls back to the durable base field.
917fn infer_scan_turn_base(
918    manifest: Option<&SessionManifest>,
919    index: Option<&TurnIndex>,
920    pending: Option<&PendingCapRewrite>,
921    file_len: u64,
922) -> u64 {
923    let marker_base = pending
924        .filter(|pending| pending.new_file_len == file_len && pending.new_file_len < pending.previous_file_len)
925        .map(|pending| pending.retained_turn_base);
926    let rewritten_base = manifest.and_then(|manifest| {
927        let previous_len = manifest.persisted_file_len?;
928        if previous_len <= file_len {
929            return None;
930        }
931        let removed_prefix = previous_len - file_len;
932        let index = index.filter(|index| index.is_valid_for_file(previous_len))?;
933        let first_retained = index
934            .entries
935            .iter()
936            .find(|entry| entry.start_offset >= removed_prefix && entry.end_offset <= previous_len)
937            .map(|entry| entry.turn_number);
938        first_retained.or_else(|| {
939            // If no indexed turn starts in the shortened file, the rewrite
940            // evicted every previously indexed turn. Preserve the next
941            // ordinal from the stale manifest so a subsequent append cannot
942            // reuse an already-observed turn number.
943            (removed_prefix >= previous_len).then(|| manifest.turn_count.saturating_add(1))
944        })
945    });
946
947    let legacy_index_base = index
948        .filter(|index| index.is_valid_for_file(file_len))
949        .and_then(|index| index.entries.front().map(|entry| entry.turn_number));
950
951    marker_base
952        .or(rewritten_base)
953        .or_else(|| manifest.and_then(|manifest| manifest.retained_turn_base))
954        .or(legacy_index_base)
955        .unwrap_or(1)
956        .max(1)
957}
958
959fn requires_full_lifecycle_validation(kind: &str) -> bool {
960    matches!(kind, "thread.started" | "thread.completed" | "turn.started" | "turn.completed" | "turn.failed")
961}
962
963fn valid_lifecycle_payload(kind: &str, line: &str) -> bool {
964    if serde_json::from_str::<VersionedThreadEvent>(line).is_err() {
965        return false;
966    }
967    if kind != "turn.completed" {
968        return true;
969    }
970    let Ok(value) = serde_json::from_str::<serde_json::Value>(line) else {
971        return false;
972    };
973    value
974        .get("event")
975        .and_then(|event| event.get("usage"))
976        .is_some_and(serde_json::Value::is_object)
977}
978
979fn decode_events(bytes: &[u8]) -> Vec<ThreadEvent> {
980    bytes
981        .split(|byte| *byte == b'\n')
982        .filter_map(|line| {
983            let line = std::str::from_utf8(line).ok()?.trim();
984            if line.is_empty() {
985                return None;
986            }
987            serde_json::from_str::<VersionedThreadEvent>(line)
988                .ok()
989                .map(VersionedThreadEvent::into_event)
990        })
991        .collect()
992}
993
994/// Count records that the authoritative scan would include in the manifest.
995/// This deliberately parses the lightweight event envelope instead of using
996/// the turn index: a cap rewrite can remove session-level records that never
997/// belong to an indexed turn.
998fn count_persisted_event_records(bytes: &[u8]) -> u64 {
999    bytes
1000        .split(|byte| *byte == b'\n')
1001        .filter_map(|line| std::str::from_utf8(line).ok())
1002        .map(str::trim)
1003        .filter(|line| !line.is_empty())
1004        .filter(|line| {
1005            let Ok(value) = serde_json::from_str::<VersionedEventKind<'_>>(line) else {
1006                return false;
1007            };
1008            let kind = value.event.kind;
1009            !requires_full_lifecycle_validation(kind) || valid_lifecycle_payload(kind, line)
1010        })
1011        .count() as u64
1012}
1013
1014#[derive(Debug, Serialize)]
1015struct EvictionSummary {
1016    session_id: String,
1017    evicted_event_count: usize,
1018    event_types: BTreeMap<String, u64>,
1019    grounded_facts: Vec<String>,
1020    created_at: String,
1021}
1022
1023/// Extract a bounded, deterministic set of facts from canonical event
1024/// payloads. This is intentionally structural rather than model-generated:
1025/// eviction must remain synchronous, reproducible, and safe when the model is
1026/// unavailable. Only completed item snapshots and terminal thread errors are
1027/// considered, so streaming deltas and raw tool output cannot flood the
1028/// derived summary.
1029fn extract_grounded_facts(events: &[ThreadEvent]) -> Vec<String> {
1030    let mut facts = Vec::new();
1031    for event in events {
1032        let candidates: Vec<String> = match event {
1033            ThreadEvent::ItemCompleted(completed) => item_facts(&completed.item.details),
1034            ThreadEvent::TurnFailed(failed) => vec![failed.message.clone()],
1035            ThreadEvent::TurnBlocked(blocked) => vec![blocked.message.clone()],
1036            ThreadEvent::Error(error) => vec![error.message.clone()],
1037            _ => Vec::new(),
1038        };
1039        for candidate in candidates {
1040            let fact = normalize_eviction_fact(&candidate);
1041            if fact.is_empty() || facts.iter().any(|existing| existing == &fact) {
1042                continue;
1043            }
1044            facts.push(fact);
1045            if facts.len() == MAX_EVICTION_GROUNDED_FACTS {
1046                return facts;
1047            }
1048        }
1049    }
1050    facts
1051}
1052
1053fn item_facts(details: &ThreadItemDetails) -> Vec<String> {
1054    match details {
1055        ThreadItemDetails::AgentMessage(item) => vec![item.text.clone()],
1056        ThreadItemDetails::Plan(item) => vec![item.text.clone()],
1057        ThreadItemDetails::FileChange(item) => item
1058            .changes
1059            .iter()
1060            .map(|change| {
1061                let kind = match change.kind {
1062                    vtcode_exec_events::PatchChangeKind::Add => "add",
1063                    vtcode_exec_events::PatchChangeKind::Delete => "delete",
1064                    vtcode_exec_events::PatchChangeKind::Update => "update",
1065                };
1066                format!("file {kind}: {}", change.path)
1067            })
1068            .collect(),
1069        ThreadItemDetails::Harness(item) => item.message.clone().into_iter().collect(),
1070        _ => Vec::new(),
1071    }
1072}
1073
1074fn normalize_eviction_fact(value: &str) -> String {
1075    let normalized = value.split_whitespace().collect::<Vec<_>>().join(" ");
1076    if normalized.len() <= MAX_EVICTION_GROUNDED_FACT_BYTES {
1077        return normalized;
1078    }
1079    let mut end = MAX_EVICTION_GROUNDED_FACT_BYTES - '…'.len_utf8();
1080    while !normalized.is_char_boundary(end) {
1081        end -= 1;
1082    }
1083    format!("{}…", &normalized[..end])
1084}
1085
1086fn default_eviction_summary_hook(derived_dir: PathBuf, session_id: String) -> EvictionSummaryHook {
1087    Arc::new(move |events| {
1088        let mut event_types = BTreeMap::new();
1089        for event in events {
1090            let kind = serde_json::to_value(event)
1091                .ok()
1092                .and_then(|value| value.get("type").and_then(|value| value.as_str()).map(str::to_owned))
1093                .unwrap_or_else(|| "unknown".to_owned());
1094            *event_types.entry(kind).or_insert(0) += 1;
1095        }
1096        let summary = EvictionSummary {
1097            session_id: session_id.clone(),
1098            evicted_event_count: events.len(),
1099            event_types,
1100            grounded_facts: extract_grounded_facts(events),
1101            created_at: now_rfc3339(),
1102        };
1103        let path = derived_dir.join(format!("eviction-summary-{}.json", uuid::Uuid::new_v4().simple()));
1104        let bytes = serde_json::to_vec(&summary)?;
1105        VtCodePaths::write_private_file_atomic(&path, &bytes)
1106            .map_err(|error| SessionStoreError::io(path, std::io::Error::other(error)))
1107    })
1108}
1109
1110impl Drop for SessionEventLog {
1111    fn drop(&mut self) {
1112        if let Ok(_eviction_guard) = self.shared.eviction_lock.lock()
1113            && let Ok(mut st) = self.shared.state.lock()
1114        {
1115            // The fallible `flush` method is the authoritative shutdown path;
1116            // Drop only provides a best-effort byte flush for callers that do
1117            // not explicitly close the log. Rewriting metadata here could
1118            // overwrite a manifest update made by another owner after the
1119            // last append.
1120            let _ = self.flush_write_buf_locked(&mut st);
1121        }
1122    }
1123}
1124
1125/// Locate the next newline at or after `from`, returning a past-the-end index.
1126fn poison<T>(_e: std::sync::PoisonError<T>) -> SessionStoreError {
1127    SessionStoreError::Io {
1128        path: PathBuf::new(),
1129        source: std::io::Error::other("session store lock poisoned"),
1130    }
1131}
1132
1133fn now_rfc3339() -> String {
1134    Utc::now().to_rfc3339()
1135}
1136
1137/// Session-level metadata persisted to `manifest.json`.
1138#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1139pub struct SessionManifest {
1140    /// Stable session identifier (directory name).
1141    pub session_id: String,
1142    /// Layout schema version (`SESSION_STORE_SCHEMA_VERSION`).
1143    schema_version: u32,
1144    /// RFC3339 creation timestamp.
1145    pub created_at: String,
1146    /// RFC3339 last-update timestamp.
1147    pub updated_at: String,
1148    /// Number of completed turns.
1149    pub turn_count: u64,
1150    /// Total number of events recorded.
1151    pub event_count: u64,
1152    /// Lifecycle status (`active` | `completed`).
1153    pub status: String,
1154    /// Whether the canonical log currently ends inside an open turn.
1155    ///
1156    /// This is optional on read so manifests written before open-turn
1157    /// persistence was introduced trigger a safe event-log scan instead of
1158    /// silently losing lifecycle state.
1159    #[serde(default)]
1160    in_turn: Option<bool>,
1161    /// Byte length covered by the persisted manifest and turn index.
1162    ///
1163    /// This is optional for compatibility with manifests written before the
1164    /// fast-path freshness guard existed; those manifests are rebuilt from the
1165    /// canonical event log on reopen.
1166    #[serde(default)]
1167    persisted_file_len: Option<u64>,
1168    /// Ordinal of the first turn retained in the canonical log.
1169    ///
1170    /// Cap eviction removes completed turns but must keep later turn numbers
1171    /// monotonic. The field lets an authoritative scan restore those ordinals
1172    /// even when the derived index is stale or missing.
1173    #[serde(default)]
1174    retained_turn_base: Option<u64>,
1175}
1176
1177impl SessionManifest {
1178    /// Number of turns preceding the retained canonical range.
1179    #[must_use]
1180    pub fn evicted_turn_count(&self) -> u64 {
1181        self.retained_turn_base.unwrap_or(1).saturating_sub(1)
1182    }
1183    /// Create a fresh manifest for a session.
1184    #[must_use]
1185    pub(crate) fn new(session_id: &str) -> Self {
1186        let ts = now_rfc3339();
1187        Self {
1188            session_id: session_id.to_string(),
1189            schema_version: crate::SESSION_STORE_SCHEMA_VERSION,
1190            created_at: ts.clone(),
1191            updated_at: ts,
1192            turn_count: 0,
1193            event_count: 0,
1194            status: "active".to_string(),
1195            in_turn: Some(false),
1196            persisted_file_len: Some(0),
1197            retained_turn_base: Some(1),
1198        }
1199    }
1200}
1201
1202/// Byte-offset index of a single turn within `events.jsonl`.
1203#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1204pub struct TurnIndexEntry {
1205    /// Turn ordinal (1-based).
1206    turn_number: u64,
1207    /// Byte offset of the turn's first event.
1208    start_offset: u64,
1209    /// Byte offset just past the turn's last event.
1210    end_offset: u64,
1211    /// Number of events in the turn.
1212    event_count: u64,
1213    /// RFC3339 timestamp of turn start.
1214    ts: String,
1215}
1216
1217/// Ordered index of all turns in a session.
1218#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
1219pub struct TurnIndex {
1220    /// Turn entries in ordinal order.
1221    entries: VecDeque<TurnIndexEntry>,
1222}
1223
1224impl TurnIndex {
1225    /// Number of indexed turns.
1226    #[must_use]
1227    pub fn len(&self) -> usize {
1228        self.entries.len()
1229    }
1230
1231    /// Whether the index is empty.
1232    #[must_use]
1233    pub fn is_empty(&self) -> bool {
1234        self.entries.is_empty()
1235    }
1236
1237    fn is_valid_for_file(&self, file_len: u64) -> bool {
1238        let mut previous_end = 0u64;
1239        self.entries.iter().all(|entry| {
1240            let valid = entry.event_count > 0
1241                && entry.start_offset >= previous_end
1242                && entry.start_offset <= entry.end_offset
1243                && entry.end_offset <= file_len;
1244            if valid {
1245                previous_end = entry.end_offset;
1246            }
1247            valid
1248        })
1249    }
1250
1251    fn is_consistent_with_manifest(&self, manifest: &SessionManifest) -> bool {
1252        let expected_last_turn = if manifest.in_turn == Some(true) {
1253            manifest.turn_count.saturating_add(1)
1254        } else {
1255            manifest.turn_count
1256        };
1257        let entries_are_contiguous = self
1258            .entries
1259            .iter()
1260            .map(|entry| entry.turn_number)
1261            .try_fold(None::<u64>, |previous, turn_number| {
1262                if previous.is_some_and(|previous| turn_number != previous.saturating_add(1)) {
1263                    return Err(());
1264                }
1265                Ok(Some(turn_number))
1266            })
1267            .is_ok();
1268        if !entries_are_contiguous {
1269            return false;
1270        }
1271
1272        let expected_first_turn = manifest.retained_turn_base.unwrap_or(1).max(1);
1273        match (self.entries.front(), self.entries.back()) {
1274            (Some(first), Some(last)) => {
1275                first.turn_number == expected_first_turn && last.turn_number == expected_last_turn
1276            }
1277            (None, None) => {
1278                expected_last_turn == 0
1279                    || manifest
1280                        .retained_turn_base
1281                        .is_some_and(|retained_turn_base| retained_turn_base > manifest.turn_count)
1282            }
1283            _ => false,
1284        }
1285    }
1286}
1287
1288#[cfg(test)]
1289mod borrowed_envelope_tests {
1290    use super::{BorrowedVersionedEvent, EVENT_SCHEMA_VERSION};
1291    use vtcode_exec_events::{
1292        ThreadEvent, ThreadStartedEvent, TurnCompletedEvent, TurnStartedEvent, Usage, VersionedThreadEvent,
1293    };
1294
1295    /// The borrowed envelope must produce JSON byte-identical to
1296    /// `VersionedThreadEvent::new(event.clone())`. This guards against drift if
1297    /// either the envelope or the canonical wrapper is modified.
1298    #[test]
1299    fn borrowed_envelope_matches_versioned_envelope() {
1300        for event in [
1301            ThreadEvent::ThreadStarted(ThreadStartedEvent { thread_id: "thread".to_string() }),
1302            ThreadEvent::TurnStarted(TurnStartedEvent::default()),
1303            ThreadEvent::TurnCompleted(TurnCompletedEvent {
1304                completed_at: None,
1305                usage: Usage::default(),
1306                in_progress_exec_sessions: Vec::new(),
1307            }),
1308        ] {
1309            let canonical =
1310                serde_json::to_string(&VersionedThreadEvent::new(event.clone())).expect("canonical serialize");
1311            let borrowed = serde_json::to_string(&BorrowedVersionedEvent {
1312                schema_version: EVENT_SCHEMA_VERSION,
1313                event: &event,
1314            })
1315            .expect("borrowed serialize");
1316            assert_eq!(canonical, borrowed, "JSON differs for {event:?}");
1317        }
1318    }
1319}
1320
1321#[cfg(test)]
1322mod lifecycle_state_machine_tests {
1323    use super::{LifecycleKind, LogState};
1324    use vtcode_exec_events::{
1325        ThreadCompletedEvent, ThreadCompletionSubtype, ThreadEvent, ThreadStartedEvent, TurnCompletedEvent,
1326        TurnFailedEvent, TurnStartedEvent, Usage,
1327    };
1328
1329    fn fresh_state() -> LogState {
1330        LogState::new("test-session")
1331    }
1332
1333    #[test]
1334    fn lifecycle_kind_from_event_covers_all_variants() {
1335        assert_eq!(
1336            LifecycleKind::from_event(&ThreadEvent::TurnStarted(TurnStartedEvent::default())),
1337            LifecycleKind::TurnStarted
1338        );
1339        assert_eq!(
1340            LifecycleKind::from_event(&ThreadEvent::TurnCompleted(TurnCompletedEvent {
1341                completed_at: None,
1342                usage: Usage::default(),
1343                in_progress_exec_sessions: Vec::new()
1344            })),
1345            LifecycleKind::TurnCompleted
1346        );
1347        assert_eq!(
1348            LifecycleKind::from_event(&ThreadEvent::TurnFailed(TurnFailedEvent {
1349                completed_at: None,
1350                message: "err".to_string(),
1351                usage: None,
1352            })),
1353            LifecycleKind::TurnFailed
1354        );
1355        assert_eq!(
1356            LifecycleKind::from_event(&ThreadEvent::ThreadStarted(ThreadStartedEvent { thread_id: "x".to_string() })),
1357            LifecycleKind::ThreadStarted
1358        );
1359        assert_eq!(
1360            LifecycleKind::from_event(&ThreadEvent::ThreadCompleted(Box::new(ThreadCompletedEvent {
1361                completed_at: None,
1362                thread_id: "x".to_string(),
1363                session_id: "x".to_string(),
1364                subtype: ThreadCompletionSubtype::Success,
1365                outcome_code: "completed".to_string(),
1366                result: None,
1367                stop_reason: None,
1368                usage: Usage::default(),
1369                total_cost_usd: None,
1370                num_turns: 1,
1371            }))),
1372            LifecycleKind::ThreadCompleted
1373        );
1374        assert_eq!(LifecycleKind::from_kind("thread.started"), LifecycleKind::ThreadStarted);
1375        assert_eq!(LifecycleKind::from_kind("thread.completed"), LifecycleKind::ThreadCompleted);
1376    }
1377
1378    #[test]
1379    fn lifecycle_kind_from_str_matches_event_discriminator() {
1380        assert_eq!(LifecycleKind::from_kind("turn.started"), LifecycleKind::TurnStarted);
1381        assert_eq!(LifecycleKind::from_kind("turn.completed"), LifecycleKind::TurnCompleted);
1382        assert_eq!(LifecycleKind::from_kind("turn.failed"), LifecycleKind::TurnFailed);
1383        assert_eq!(LifecycleKind::from_kind("tool.called"), LifecycleKind::Other);
1384        assert_eq!(LifecycleKind::from_kind("thread.started"), LifecycleKind::ThreadStarted);
1385        assert_eq!(LifecycleKind::from_kind("thread.completed"), LifecycleKind::ThreadCompleted);
1386    }
1387
1388    #[test]
1389    fn turn_started_pushes_index_entry_and_sets_in_turn() {
1390        let mut st = fresh_state();
1391        st.manifest.status = "completed".to_string();
1392        let is_boundary = st.apply_lifecycle_event(LifecycleKind::TurnStarted, 0, 100);
1393        assert!(!is_boundary, "TurnStarted is not a turn boundary");
1394        assert!(st.in_turn);
1395        assert_eq!(st.manifest.status, "active");
1396        assert_eq!(st.index.entries.len(), 1);
1397        let entry = &st.index.entries[0];
1398        assert_eq!(entry.turn_number, 1);
1399        assert_eq!(entry.start_offset, 0);
1400        assert_eq!(entry.end_offset, 100);
1401        assert_eq!(entry.event_count, 1);
1402    }
1403
1404    #[test]
1405    fn intermediate_events_extend_current_turn() {
1406        let mut st = fresh_state();
1407        st.apply_lifecycle_event(LifecycleKind::TurnStarted, 0, 100);
1408        // Simulate two intermediate events.
1409        let is_b1 = st.apply_lifecycle_event(LifecycleKind::Other, 100, 200);
1410        let is_b2 = st.apply_lifecycle_event(LifecycleKind::Other, 200, 300);
1411        assert!(!is_b1 && !is_b2);
1412        assert!(st.in_turn);
1413        assert_eq!(st.index.entries.len(), 1);
1414        let entry = &st.index.entries[0];
1415        assert_eq!(entry.end_offset, 300);
1416        assert_eq!(entry.event_count, 3);
1417    }
1418
1419    #[test]
1420    fn turn_completed_closes_turn_and_returns_boundary() {
1421        let mut st = fresh_state();
1422        st.apply_lifecycle_event(LifecycleKind::TurnStarted, 0, 100);
1423        st.apply_lifecycle_event(LifecycleKind::Other, 100, 200);
1424        let is_boundary = st.apply_lifecycle_event(LifecycleKind::TurnCompleted, 200, 300);
1425        assert!(is_boundary);
1426        assert!(!st.in_turn);
1427        assert_eq!(st.manifest.turn_count, 1);
1428        assert_eq!(st.manifest.status, "active");
1429        st.apply_lifecycle_event(LifecycleKind::ThreadCompleted, 300, 400);
1430        assert_eq!(st.manifest.status, "completed");
1431        let entry = &st.index.entries[0];
1432        assert_eq!(entry.end_offset, 300);
1433        assert_eq!(entry.event_count, 3);
1434    }
1435
1436    #[test]
1437    fn turn_failed_closes_turn_without_terminal_thread_status() {
1438        let mut st = fresh_state();
1439        st.apply_lifecycle_event(LifecycleKind::TurnStarted, 0, 100);
1440        let is_boundary = st.apply_lifecycle_event(LifecycleKind::TurnFailed, 100, 200);
1441        assert!(is_boundary);
1442        assert!(!st.in_turn);
1443        assert_eq!(st.manifest.turn_count, 1);
1444        assert_eq!(st.manifest.status, "active");
1445        st.apply_lifecycle_event(LifecycleKind::ThreadCompleted, 200, 300);
1446        assert_eq!(st.manifest.status, "completed");
1447    }
1448
1449    #[test]
1450    fn turn_completed_without_turn_started_is_idempotent() {
1451        let mut st = fresh_state();
1452        // Receiving TurnCompleted without a preceding TurnStarted should not
1453        // panic or corrupt the index; terminal status remains active until the
1454        // thread lifecycle itself completes.
1455        let is_boundary = st.apply_lifecycle_event(LifecycleKind::TurnCompleted, 0, 100);
1456        assert!(is_boundary);
1457        assert!(!st.in_turn);
1458        assert_eq!(st.manifest.turn_count, 0, "no turn was started");
1459        assert_eq!(st.manifest.status, "active");
1460        st.apply_lifecycle_event(LifecycleKind::ThreadCompleted, 100, 200);
1461        assert_eq!(st.manifest.status, "completed");
1462        assert!(st.index.entries.is_empty());
1463    }
1464
1465    #[test]
1466    fn multiple_turns_get_incrementing_ordinals() {
1467        let mut st = fresh_state();
1468        for n in 1..=3 {
1469            st.apply_lifecycle_event(LifecycleKind::TurnStarted, n * 100, n * 100 + 50);
1470            st.apply_lifecycle_event(LifecycleKind::TurnCompleted, n * 100 + 50, n * 100 + 100);
1471        }
1472        assert_eq!(st.index.entries.len(), 3);
1473        for (i, entry) in st.index.entries.iter().enumerate() {
1474            assert_eq!(entry.turn_number, (i + 1) as u64);
1475        }
1476        assert_eq!(st.manifest.turn_count, 3);
1477    }
1478}
1479
1480#[cfg(test)]
1481mod cap_eviction_tests {
1482    use super::{LogState, TurnIndexEntry};
1483
1484    /// Build a `LogState` with `turns` fake turns, each having `events_per_turn`
1485    /// events, starting at byte offset 0.
1486    fn state_with_turns(turns: usize, events_per_turn: u64) -> LogState {
1487        let mut st = LogState::new("cap-test");
1488        st.manifest.event_count = (turns as u64) * events_per_turn;
1489        let mut offset = 0u64;
1490        for n in 1..=turns {
1491            st.index.entries.push_back(TurnIndexEntry {
1492                turn_number: n as u64,
1493                start_offset: offset,
1494                end_offset: offset + events_per_turn * 10,
1495                event_count: events_per_turn,
1496                ts: "2026-01-01T00:00:00Z".to_string(),
1497            });
1498            offset += events_per_turn * 10;
1499        }
1500        st
1501    }
1502
1503    #[test]
1504    fn no_eviction_when_under_cap() {
1505        let st = state_with_turns(3, 2); // 6 events
1506        assert!(st.plan_cap_eviction(10).is_none());
1507        assert_eq!(st.index.entries.len(), 3, "no turns should be evicted");
1508    }
1509
1510    #[test]
1511    fn no_eviction_when_cap_disabled() {
1512        let st = state_with_turns(5, 2); // 10 events
1513        assert!(st.plan_cap_eviction(0).is_none());
1514        assert_eq!(st.index.entries.len(), 5);
1515    }
1516
1517    #[test]
1518    fn evicts_oldest_turns_to_meet_cap() {
1519        // 5 turns × 2 events = 10 events; cap = 6 → need to evict 2 turns (4 events).
1520        let st = state_with_turns(5, 2);
1521        let plan = st.plan_cap_eviction(6).expect("eviction planned");
1522        assert_eq!(plan.evicted_event_count, 4, "should evict 4 events (2 turns)");
1523        assert_eq!(st.index.entries.len(), 5, "planning must not mutate state");
1524        // Truncate offset is the end of the last evicted turn.
1525        assert_eq!(plan.truncate_offset, 40); // 2 turns × 20 bytes each
1526
1527        // Applying the plan leaves turns 3, 4, 5.
1528        let mut st = st;
1529        st.apply_cap_eviction(plan, 60);
1530        assert_eq!(st.index.entries.len(), 3, "should keep 3 turns");
1531        assert_eq!(st.index.entries[0].turn_number, 3);
1532        assert_eq!(st.index.entries[2].turn_number, 5);
1533    }
1534
1535    #[test]
1536    fn evicts_all_turns_when_cap_smaller_than_one_turn() {
1537        // 3 turns × 5 events = 15 events; cap = 3 → evict turns until ≤ 3 remain.
1538        // Each turn has 5 events, so evicting 2 turns leaves 5 (>3), evicting
1539        // 3 turns leaves 0.
1540        let st = state_with_turns(3, 5);
1541        let plan = st.plan_cap_eviction(3).expect("eviction planned");
1542        assert_eq!(plan.evicted_event_count, 15, "all events evicted");
1543        let mut st = st;
1544        st.apply_cap_eviction(plan, 0);
1545        assert_eq!(st.index.entries.len(), 0);
1546    }
1547}