Skip to main content

reconstruct_context

Function reconstruct_context 

Source
pub fn reconstruct_context(entries: &[SessionEntry]) -> Vec<AgentMessage>
Expand description

Reconstruct agent messages from session entries for resume.

Two modes:

  1. Active-branch mode (with Leaf entries). The session file holds leaf pointer entries that record the active branch tip. When one or more Leaf entries are present, this function uses the last Leaf’s entry_id as the tip and walks the parent chain backward via parent_id, collecting only the entries on that branch. This is required for any session that contains branches — file-order replay would otherwise interleave messages from sibling branches into the reconstructed context.

  2. Legacy linear mode (no Leaf entries). Sessions written by the current runtime do not yet emit Leaf markers; for those the entire file is one linear branch and we replay every Message/Compaction entry in file order.

Compaction entries are honored in both modes by replaying their semantics: when a Compaction entry is encountered, every previously collected message that precedes the entry whose id equals first_kept_entry_id is dropped, the compaction summary is inserted in its place, and the kept tail (already persisted before the marker) is preserved. Messages written after the compaction marker are then appended as usual.

Defensive fallback: if a Compaction entry’s first_kept_entry_id does not match any collected entry (corrupt or forward-incompatible session), the pre-summary buffer is dropped entirely so the summary still appears and post-compaction entries continue to accumulate.