Skip to main content

lean_ctx_ext/core/context_snapshot/
builder.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Builds a [`ContextSnapshotV1`] from the live context stores (GL #1024).
3//!
4//! The builder is split into **pure projections** (`*_from_*` / `*_slice`),
5//! which map a loaded store into a bounded snapshot slice and are unit-tested
6//! with in-memory fixtures, and **impure anchors** (`git_anchor`,
7//! `project_slice`), which read git / the filesystem. [`build`] orchestrates
8//! them and finalizes the id (signing it when requested); [`create`] additionally
9//! persists the snapshot and appends it to the append-only timeline.
10
11use std::path::Path;
12use std::time::Duration;
13
14use crate::core::context_field::ContextState;
15use crate::core::context_ir::{ContextIrSourceKindV1, ContextIrTotalsV1, ContextIrV1};
16use crate::core::context_ledger::ContextLedger;
17use crate::core::session::SessionState;
18
19use super::digest::finalize_id;
20use super::signing::sign_snapshot;
21use super::types::{
22    ContextSnapshotV1, GitAnchorV1, MAX_SNAPSHOT_LEDGER_ITEMS, MAX_SNAPSHOT_LINEAGE_ITEMS,
23    MAX_SNAPSHOT_SESSION_LIST, SnapshotLedgerItemV1, SnapshotLedgerV1, SnapshotLineageItemV1,
24    SnapshotLineageV1, SnapshotProjectV1, SnapshotRoiV1, SnapshotSessionV1,
25};
26
27/// Inputs for building a snapshot.
28pub struct SnapshotOptions {
29    /// Project root the snapshot is anchored to.
30    pub project_root: String,
31    /// Sign the snapshot with the publisher keypair (else just finalize the id).
32    pub sign: bool,
33}
34
35/// Build an in-memory snapshot from the current store state, finalizing its id
36/// (and signing it when `opts.sign`). Does not persist anything.
37pub(crate) fn build(opts: &SnapshotOptions) -> Result<ContextSnapshotV1, String> {
38    let mut snap = ContextSnapshotV1::new(
39        lean_ctx_time::UtcDateTime::now().to_rfc3339(),
40        env!("CARGO_PKG_VERSION").to_string(),
41    );
42    snap.git = git_anchor(&opts.project_root);
43    snap.project = project_slice(&opts.project_root);
44
45    let ir = ContextIrV1::load();
46    snap.roi = roi_from_totals(&ir.totals);
47    snap.lineage = lineage_from_ir(&ir);
48
49    snap.ledger = ledger_slice(&ContextLedger::load());
50    snap.session =
51        SessionState::load_latest_for_project_root(&opts.project_root).map(|s| session_slice(&s));
52
53    snap.parent_id = super::timeline::head_id(&opts.project_root);
54
55    if opts.sign {
56        let (key, _newly_created) = crate::core::context_package::keys::load_or_create()?;
57        sign_snapshot(&mut snap, &key)?;
58    } else {
59        finalize_id(&mut snap)?;
60    }
61    Ok(snap)
62}
63
64/// Build, persist, and append the snapshot to the project's timeline.
65pub fn create(opts: &SnapshotOptions) -> Result<ContextSnapshotV1, String> {
66    let snap = build(opts)?;
67    super::timeline::write_snapshot(&opts.project_root, &snap)?;
68    Ok(snap)
69}
70
71// --- pure projections -------------------------------------------------------
72
73fn roi_from_totals(t: &ContextIrTotalsV1) -> SnapshotRoiV1 {
74    let denom = t.input_tokens + t.tokens_saved;
75    let compression_rate = if denom == 0 {
76        0.0
77    } else {
78        t.tokens_saved as f64 / denom as f64
79    };
80    SnapshotRoiV1 {
81        input_tokens: t.input_tokens,
82        output_tokens: t.output_tokens,
83        tokens_saved: t.tokens_saved,
84        compression_rate,
85    }
86}
87
88fn lineage_from_ir(ir: &ContextIrV1) -> SnapshotLineageV1 {
89    let start = ir.items.len().saturating_sub(MAX_SNAPSHOT_LINEAGE_ITEMS);
90    let items = ir.items[start..]
91        .iter()
92        .map(|it| SnapshotLineageItemV1 {
93            seq: it.seq,
94            kind: kind_str(&it.source.kind).to_string(),
95            tool: it.source.tool.clone(),
96            path: it.source.path.clone(),
97            input_tokens: it.input_tokens as u64,
98            output_tokens: it.output_tokens as u64,
99            compression_ratio: it.compression_ratio,
100            content_hash: it.verification.content_md5.clone(),
101        })
102        .collect();
103    SnapshotLineageV1 {
104        items_recorded: ir.totals.items_recorded,
105        items,
106    }
107}
108
109fn ledger_slice(led: &ContextLedger) -> SnapshotLedgerV1 {
110    let start = led.entries.len().saturating_sub(MAX_SNAPSHOT_LEDGER_ITEMS);
111    let items = led.entries[start..]
112        .iter()
113        .map(|e| SnapshotLedgerItemV1 {
114            path: e.path.clone(),
115            state: state_str(e.state.unwrap_or(ContextState::Candidate)).to_string(),
116            phi: e.phi,
117            sent_tokens: e.sent_tokens,
118            original_tokens: e.original_tokens,
119        })
120        .collect();
121    SnapshotLedgerV1 {
122        window_size: led.window_size,
123        total_tokens_sent: led.total_tokens_sent,
124        total_tokens_saved: led.total_tokens_saved,
125        items,
126    }
127}
128
129fn session_slice(s: &SessionState) -> SnapshotSessionV1 {
130    SnapshotSessionV1 {
131        session_id: Some(s.id.clone()),
132        task: s.task.as_ref().map(|t| t.description.clone()),
133        decisions: s
134            .decisions
135            .iter()
136            .take(MAX_SNAPSHOT_SESSION_LIST)
137            .map(|d| d.summary.clone())
138            .collect(),
139        files_touched: s
140            .files_touched
141            .iter()
142            .take(MAX_SNAPSHOT_SESSION_LIST)
143            .map(|f| f.path.clone())
144            .collect(),
145        progress_pct: s.task.as_ref().and_then(|t| t.progress_pct),
146    }
147}
148
149// --- impure anchors ---------------------------------------------------------
150
151fn project_slice(project_root: &str) -> SnapshotProjectV1 {
152    SnapshotProjectV1 {
153        root_hash: Some(crate::core::project_hash::hash_project_root(project_root)),
154        identity_hash: crate::core::project_hash::project_identity(project_root)
155            .map(|id| crate::core::hasher::hash_str(&id)),
156    }
157}
158
159fn git_anchor(project_root: &str) -> GitAnchorV1 {
160    if !crate::core::git::git_available() {
161        return GitAnchorV1::default();
162    }
163    let root = Path::new(project_root);
164    let commit = git_str(root, &["rev-parse", "HEAD"]);
165    let branch = git_str(root, &["rev-parse", "--abbrev-ref", "HEAD"]);
166    let dirty = crate::core::git::run_git(
167        &["status", "--porcelain"],
168        root,
169        Duration::from_secs(5),
170        &[],
171    )
172    .is_ok_and(|o| o.success && !o.stdout.trim().is_empty());
173    GitAnchorV1 {
174        commit,
175        branch,
176        dirty,
177    }
178}
179
180fn git_str(root: &Path, args: &[&str]) -> Option<String> {
181    crate::core::git::run_git(args, root, Duration::from_secs(5), &[])
182        .ok()
183        .filter(|o| o.success)
184        .map(|o| o.stdout.trim().to_string())
185        .filter(|s| !s.is_empty())
186}
187
188fn kind_str(k: &ContextIrSourceKindV1) -> &'static str {
189    match k {
190        ContextIrSourceKindV1::Read => "read",
191        ContextIrSourceKindV1::Shell => "shell",
192        ContextIrSourceKindV1::Search => "search",
193        ContextIrSourceKindV1::Provider => "provider",
194        ContextIrSourceKindV1::Other => "other",
195    }
196}
197
198fn state_str(s: ContextState) -> &'static str {
199    match s {
200        ContextState::Candidate => "candidate",
201        ContextState::Included => "included",
202        ContextState::Excluded => "excluded",
203        ContextState::Pinned => "pinned",
204        ContextState::Stale => "stale",
205        ContextState::Shadowed => "shadowed",
206    }
207}
208
209#[cfg(test)]
210mod tests {
211    use super::*;
212    use crate::core::context_ir::{
213        ContextIrItemV1, ContextIrSafetyV1, ContextIrSourceV1, ContextIrVerificationV1,
214    };
215    use crate::core::session::{Decision, FileTouched, TaskInfo};
216
217    fn ir_item(seq: u64, kind: ContextIrSourceKindV1, path: &str) -> ContextIrItemV1 {
218        ContextIrItemV1 {
219            seq,
220            created_at: "2026-06-28T00:00:00Z".into(),
221            source: ContextIrSourceV1 {
222                kind,
223                tool: "ctx_read".into(),
224                path: Some(path.into()),
225                ..Default::default()
226            },
227            input_tokens: 500,
228            output_tokens: 13,
229            duration_us: 0,
230            compression_ratio: 0.974,
231            content_excerpt: String::new(),
232            truncated: false,
233            safety: ContextIrSafetyV1::default(),
234            verification: ContextIrVerificationV1 {
235                content_md5: Some("c".repeat(64)),
236            },
237        }
238    }
239
240    #[test]
241    fn roi_handles_zero_and_normal() {
242        let zero = roi_from_totals(&ContextIrTotalsV1::default());
243        assert_eq!(zero.compression_rate, 0.0);
244
245        let t = ContextIrTotalsV1 {
246            items_recorded: 3,
247            input_tokens: 200,
248            output_tokens: 50,
249            tokens_saved: 600,
250        };
251        let roi = roi_from_totals(&t);
252        assert_eq!(roi.tokens_saved, 600);
253        assert!(
254            (roi.compression_rate - 0.75).abs() < 1e-9,
255            "600/(200+600)=0.75"
256        );
257    }
258
259    #[test]
260    fn lineage_maps_fields_and_bounds_to_cap() {
261        let mut ir = ContextIrV1::new();
262        ir.totals.items_recorded = 999;
263        for seq in 0..(MAX_SNAPSHOT_LINEAGE_ITEMS as u64 + 10) {
264            ir.items
265                .push(ir_item(seq, ContextIrSourceKindV1::Read, "src/a.rs"));
266        }
267        let slice = lineage_from_ir(&ir);
268        assert_eq!(slice.items_recorded, 999);
269        assert_eq!(slice.items.len(), MAX_SNAPSHOT_LINEAGE_ITEMS);
270        // The cap keeps the most recent items (tail of the IR ring).
271        assert_eq!(
272            slice.items.last().unwrap().seq,
273            MAX_SNAPSHOT_LINEAGE_ITEMS as u64 + 9
274        );
275        let first = &slice.items[0];
276        assert_eq!(first.kind, "read");
277        assert_eq!(first.tool, "ctx_read");
278        assert_eq!(first.path.as_deref(), Some("src/a.rs"));
279    }
280
281    #[test]
282    fn ledger_slice_maps_state_and_phi() {
283        let mut led = ContextLedger::new();
284        led.record("src/a.rs", "full", 500, 13);
285        led.update_phi("src/a.rs", 0.9);
286        led.set_state("src/a.rs", ContextState::Pinned);
287        led.record("src/b.rs", "signatures", 800, 40);
288
289        let slice = ledger_slice(&led);
290        assert_eq!(slice.items.len(), 2);
291        let a = slice.items.iter().find(|i| i.path == "src/a.rs").unwrap();
292        assert_eq!(a.state, "pinned");
293        assert_eq!(a.phi, Some(0.9));
294        // record() marks a fresh entry as included (it just entered the window);
295        // the candidate fallback only applies to entries with no recorded state.
296        let b = slice.items.iter().find(|i| i.path == "src/b.rs").unwrap();
297        assert_eq!(b.state, "included");
298    }
299
300    #[test]
301    fn session_slice_projects_task_and_lists() {
302        let mut s = SessionState::new();
303        s.task = Some(TaskInfo {
304            description: "Implement timeline".into(),
305            intent: None,
306            progress_pct: Some(40),
307        });
308        s.decisions.push(Decision {
309            summary: "JSONL append-only index".into(),
310            rationale: None,
311            timestamp: lean_ctx_time::UtcDateTime::now(),
312        });
313        s.files_touched.push(FileTouched {
314            path: "rust/src/core/context_snapshot/timeline.rs".into(),
315            file_ref: None,
316            read_count: 1,
317            modified: true,
318            last_mode: "full".into(),
319            tokens: 100,
320            stale: false,
321            context_item_id: None,
322            summary: None,
323        });
324
325        let slice = session_slice(&s);
326        assert_eq!(slice.task.as_deref(), Some("Implement timeline"));
327        assert_eq!(slice.progress_pct, Some(40));
328        assert_eq!(slice.decisions, vec!["JSONL append-only index".to_string()]);
329        assert_eq!(
330            slice.files_touched,
331            vec!["rust/src/core/context_snapshot/timeline.rs".to_string()]
332        );
333    }
334
335    #[test]
336    fn kind_and_state_strings_are_snake_case() {
337        assert_eq!(kind_str(&ContextIrSourceKindV1::Provider), "provider");
338        assert_eq!(state_str(ContextState::Shadowed), "shadowed");
339    }
340}