Skip to main content

lean_ctx/core/
ccp_session_bundle.rs

1use chrono::{DateTime, Utc};
2use serde::{Deserialize, Serialize};
3use std::path::{Path, PathBuf};
4
5use crate::core::session::{
6    Decision, EvidenceRecord, FileTouched, Finding, ProgressEntry, SessionState, SessionStats,
7    TaskInfo, TestSnapshot,
8};
9
10const MAX_BUNDLE_BYTES: usize = 250_000;
11const MAX_NEXT_STEPS: usize = 25;
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub enum BundlePrivacyV1 {
15    Redacted,
16    Full,
17}
18
19impl BundlePrivacyV1 {
20    pub fn parse(s: Option<&str>) -> Self {
21        match s.unwrap_or("redacted").trim().to_lowercase().as_str() {
22            "full" => Self::Full,
23            _ => Self::Redacted,
24        }
25    }
26}
27
28#[derive(Debug, Clone, Serialize, Deserialize)]
29pub struct CcpSessionBundleV1 {
30    pub schema_version: u32,
31    pub exported_at: DateTime<Utc>,
32    pub project: ProjectIdentityV1,
33    pub role: PolicyIdentityV1,
34    pub profile: PolicyIdentityV1,
35    pub session: SessionExcerptV1,
36}
37
38#[derive(Debug, Clone, Serialize, Deserialize)]
39pub struct ProjectIdentityV1 {
40    pub project_root_hash: Option<String>,
41    pub project_identity_hash: Option<String>,
42}
43
44#[derive(Debug, Clone, Serialize, Deserialize)]
45pub struct PolicyIdentityV1 {
46    pub name: String,
47    pub policy_md5: String,
48}
49
50#[derive(Debug, Clone, Serialize, Deserialize)]
51pub struct SessionExcerptV1 {
52    pub id: String,
53    pub version: u32,
54    pub started_at: DateTime<Utc>,
55    pub updated_at: DateTime<Utc>,
56    pub project_root: Option<String>,
57    pub shell_cwd: Option<String>,
58    pub task: Option<TaskInfo>,
59    pub findings: Vec<Finding>,
60    pub decisions: Vec<Decision>,
61    pub files_touched: Vec<FileTouched>,
62    pub test_results: Option<TestSnapshot>,
63    pub progress: Vec<ProgressEntry>,
64    pub next_steps: Vec<String>,
65    pub evidence: Vec<EvidenceRecord>,
66    pub stats: SessionStats,
67    #[serde(default)]
68    pub terse_mode: bool,
69}
70
71pub fn build_bundle_v1(session: &SessionState, privacy: BundlePrivacyV1) -> CcpSessionBundleV1 {
72    let role_name = crate::core::roles::active_role_name();
73    let role = crate::core::roles::active_role();
74    let profile_name = crate::core::profiles::active_profile_name();
75    let profile = crate::core::profiles::active_profile();
76
77    let role_policy_md5 = md5_hex(&serde_json::to_string(&role).unwrap_or_default());
78    let profile_policy_md5 = md5_hex(&serde_json::to_string(&profile).unwrap_or_default());
79
80    let (project_root_hash, project_identity_hash) =
81        session
82            .project_root
83            .as_deref()
84            .map_or((None, None), |root| {
85                let root_hash = crate::core::project_hash::hash_project_root(root);
86                let identity = crate::core::project_hash::project_identity(root);
87                let identity_hash = identity.as_deref().map(md5_hex);
88                (Some(root_hash), identity_hash)
89            });
90
91    let mut excerpt = SessionExcerptV1 {
92        id: session.id.clone(),
93        version: session.version,
94        started_at: session.started_at,
95        updated_at: session.updated_at,
96        project_root: session.project_root.clone(),
97        shell_cwd: session.shell_cwd.clone(),
98        task: session.task.clone(),
99        findings: session.findings.clone(),
100        decisions: session.decisions.clone(),
101        files_touched: session.files_touched.clone(),
102        test_results: session.test_results.clone(),
103        progress: session.progress.clone(),
104        next_steps: session
105            .next_steps
106            .iter()
107            .take(MAX_NEXT_STEPS)
108            .cloned()
109            .collect(),
110        evidence: session.evidence.clone(),
111        stats: session.stats.clone(),
112        terse_mode: session.terse_mode,
113    };
114
115    // Path minimization: prefer relative paths when project_root is known.
116    let root = excerpt.project_root.clone().unwrap_or_default();
117    if !root.is_empty() {
118        for f in &mut excerpt.files_touched {
119            if let Some(rel) = strip_root_prefix(&root, &f.path) {
120                f.path = rel;
121            }
122        }
123        for finding in &mut excerpt.findings {
124            if let Some(ref file) = finding.file.clone() {
125                if let Some(rel) = strip_root_prefix(&root, file) {
126                    finding.file = Some(rel);
127                }
128            }
129        }
130    }
131
132    match privacy {
133        BundlePrivacyV1::Full => {
134            // Full export is allowed only for admin role; otherwise force redaction.
135            if role_name != "admin" {
136                redact_excerpt_in_place(&mut excerpt);
137            } else if crate::core::redaction::redaction_enabled_for_active_role() {
138                // Admin opted into redaction — keep it consistent.
139                redact_excerpt_in_place(&mut excerpt);
140            }
141        }
142        BundlePrivacyV1::Redacted => {
143            redact_excerpt_in_place(&mut excerpt);
144        }
145    }
146
147    CcpSessionBundleV1 {
148        schema_version: crate::core::contracts::CCP_SESSION_BUNDLE_V1_SCHEMA_VERSION,
149        exported_at: Utc::now(),
150        project: ProjectIdentityV1 {
151            project_root_hash,
152            project_identity_hash,
153        },
154        role: PolicyIdentityV1 {
155            name: role_name,
156            policy_md5: role_policy_md5,
157        },
158        profile: PolicyIdentityV1 {
159            name: profile_name,
160            policy_md5: profile_policy_md5,
161        },
162        session: excerpt,
163    }
164}
165
166pub fn serialize_bundle_v1_pretty(bundle: &CcpSessionBundleV1) -> Result<String, String> {
167    let json = serde_json::to_string_pretty(bundle).map_err(|e| e.to_string())?;
168    if json.len() > MAX_BUNDLE_BYTES {
169        return Err(format!(
170            "ERROR: bundle too large ({} bytes > max {}). Use privacy=redacted and/or reduce session evidence.",
171            json.len(),
172            MAX_BUNDLE_BYTES
173        ));
174    }
175    Ok(json)
176}
177
178pub fn parse_bundle_v1(json: &str) -> Result<CcpSessionBundleV1, String> {
179    let b: CcpSessionBundleV1 = serde_json::from_str(json).map_err(|e| e.to_string())?;
180    if b.schema_version != crate::core::contracts::CCP_SESSION_BUNDLE_V1_SCHEMA_VERSION {
181        return Err(format!(
182            "ERROR: unsupported schema_version {} (expected {})",
183            b.schema_version,
184            crate::core::contracts::CCP_SESSION_BUNDLE_V1_SCHEMA_VERSION
185        ));
186    }
187    Ok(b)
188}
189
190pub fn write_bundle_v1(path: &Path, json: &str) -> Result<(), String> {
191    let parent = path
192        .parent()
193        .ok_or_else(|| "ERROR: invalid path".to_string())?;
194    if !parent.exists() {
195        std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
196    }
197    let tmp = parent.join(format!(
198        ".{}.tmp",
199        path.file_name()
200            .and_then(|s| s.to_str())
201            .unwrap_or("bundle")
202    ));
203    std::fs::write(&tmp, json).map_err(|e| e.to_string())?;
204    std::fs::rename(&tmp, path).map_err(|e| e.to_string())?;
205    Ok(())
206}
207
208pub fn read_bundle_v1(path: &Path) -> Result<CcpSessionBundleV1, String> {
209    let json = std::fs::read_to_string(path).map_err(|e| e.to_string())?;
210    if json.len() > MAX_BUNDLE_BYTES {
211        return Err(format!(
212            "ERROR: bundle file too large ({} bytes > max {})",
213            json.len(),
214            MAX_BUNDLE_BYTES
215        ));
216    }
217    parse_bundle_v1(&json)
218}
219
220pub fn import_bundle_v1_into_session(
221    session: &mut SessionState,
222    bundle: &CcpSessionBundleV1,
223    current_project_root: Option<&str>,
224) -> ImportReportV1 {
225    let mut imported = bundle.session.clone();
226
227    // Prefer current project root when provided (replay safety).
228    if let Some(root) = current_project_root {
229        imported.project_root = Some(root.to_string());
230    }
231
232    // Mark stale file paths if missing or outside jail.
233    let jail_root = imported.project_root.clone().unwrap_or_else(|| {
234        std::env::current_dir()
235            .map_or_else(|_| ".".to_string(), |p| p.to_string_lossy().to_string())
236    });
237    let jail_root_path = PathBuf::from(&jail_root);
238
239    let mut stale = 0u32;
240    for f in &mut imported.files_touched {
241        let candidate = candidate_path(&jail_root_path, &f.path);
242        if let Ok((jailed, _warning)) = crate::core::io_boundary::jail_and_check_path(
243            "ctx_session.import",
244            candidate.as_path(),
245            jail_root_path.as_path(),
246        ) {
247            if jailed.exists() {
248                f.stale = false;
249            } else {
250                f.stale = true;
251                stale += 1;
252            }
253        } else {
254            f.stale = true;
255            stale += 1;
256        }
257    }
258
259    *session = SessionState {
260        id: imported.id.clone(),
261        version: imported.version,
262        started_at: imported.started_at,
263        updated_at: imported.updated_at,
264        project_root: imported.project_root.clone(),
265        shell_cwd: imported.shell_cwd.clone(),
266        task: imported.task.clone(),
267        findings: imported.findings.clone(),
268        decisions: imported.decisions.clone(),
269        files_touched: imported.files_touched.clone(),
270        test_results: imported.test_results.clone(),
271        progress: imported.progress.clone(),
272        next_steps: imported.next_steps.clone(),
273        evidence: imported.evidence.clone(),
274        intents: Vec::new(),
275        active_structured_intent: None,
276        stats: imported.stats.clone(),
277        terse_mode: imported.terse_mode,
278    };
279
280    ImportReportV1 {
281        session_id: session.id.clone(),
282        version: session.version,
283        files_touched: session.files_touched.len() as u32,
284        stale_files: stale,
285    }
286}
287
288#[derive(Debug, Clone)]
289pub struct ImportReportV1 {
290    pub session_id: String,
291    pub version: u32,
292    pub files_touched: u32,
293    pub stale_files: u32,
294}
295
296fn redact_excerpt_in_place(ex: &mut SessionExcerptV1) {
297    ex.shell_cwd = None;
298    // project_root is represented as hashes at bundle level; avoid exporting raw paths.
299    ex.project_root = None;
300
301    if let Some(ref mut t) = ex.task {
302        t.description = crate::core::redaction::redact_text(&t.description);
303        if let Some(ref mut intent) = t.intent {
304            *intent = crate::core::redaction::redact_text(intent);
305        }
306    }
307    for f in &mut ex.findings {
308        f.summary = crate::core::redaction::redact_text(&f.summary);
309        if let Some(ref mut file) = f.file {
310            *file = crate::core::redaction::redact_text(file);
311        }
312    }
313    for d in &mut ex.decisions {
314        d.summary = crate::core::redaction::redact_text(&d.summary);
315        if let Some(ref mut r) = d.rationale {
316            *r = crate::core::redaction::redact_text(r);
317        }
318    }
319    for p in &mut ex.progress {
320        p.action = crate::core::redaction::redact_text(&p.action);
321        if let Some(ref mut detail) = p.detail {
322            *detail = crate::core::redaction::redact_text(detail);
323        }
324    }
325    for s in &mut ex.next_steps {
326        *s = crate::core::redaction::redact_text(s);
327    }
328    for ev in &mut ex.evidence {
329        ev.value = None;
330    }
331}
332
333fn strip_root_prefix(root: &str, path: &str) -> Option<String> {
334    let root = root.trim_end_matches(std::path::MAIN_SEPARATOR);
335    let root_prefix = format!("{root}{}", std::path::MAIN_SEPARATOR);
336    if path.starts_with(&root_prefix) {
337        Some(path.trim_start_matches(&root_prefix).to_string())
338    } else {
339        None
340    }
341}
342
343fn candidate_path(jail_root: &Path, stored_path: &str) -> PathBuf {
344    let p = PathBuf::from(stored_path);
345    if p.is_absolute() {
346        p
347    } else {
348        jail_root.join(p)
349    }
350}
351
352fn md5_hex(text: &str) -> String {
353    use md5::{Digest, Md5};
354    let mut hasher = Md5::new();
355    hasher.update(text.as_bytes());
356    format!("{:x}", hasher.finalize())
357}
358
359#[cfg(test)]
360mod tests {
361    use super::*;
362
363    #[test]
364    fn redacted_export_drops_evidence_values() {
365        let mut s = SessionState::new();
366        s.record_manual_evidence("k", Some("secret=abcdef0123456789abcdef0123456789"));
367        let b = build_bundle_v1(&s, BundlePrivacyV1::Redacted);
368        assert!(b.session.evidence.iter().all(|e| e.value.is_none()));
369    }
370
371    #[test]
372    fn serialize_respects_size_cap() {
373        let s = SessionState::new();
374        let b = build_bundle_v1(&s, BundlePrivacyV1::Redacted);
375        let json = serialize_bundle_v1_pretty(&b).expect("json");
376        assert!(json.len() < MAX_BUNDLE_BYTES);
377        let parsed = parse_bundle_v1(&json).expect("parse");
378        assert_eq!(parsed.schema_version, b.schema_version);
379    }
380
381    #[test]
382    fn import_marks_missing_files_stale() {
383        let mut s = SessionState::new();
384        s.project_root = Some(
385            std::env::current_dir()
386                .unwrap()
387                .to_string_lossy()
388                .to_string(),
389        );
390        s.touch_file("does-not-exist-xyz.txt", None, "full", 10);
391        let b = build_bundle_v1(&s, BundlePrivacyV1::Redacted);
392
393        let root = std::env::current_dir()
394            .unwrap()
395            .to_string_lossy()
396            .to_string();
397        let mut target = SessionState::new();
398        let report = import_bundle_v1_into_session(&mut target, &b, Some(&root));
399        assert_eq!(report.files_touched, 1);
400        assert_eq!(report.stale_files, 1);
401        assert!(target.files_touched[0].stale);
402    }
403}