Skip to main content

fetchium_core/collab/
branch.rs

1//! Research session branching (PRD §37).
2
3use crate::error::FetchiumError;
4use serde::{Deserialize, Serialize};
5
6#[derive(Debug, Clone, Serialize, Deserialize)]
7pub struct SessionMeta {
8    pub id: String,
9    pub name: String,
10    pub created_at: String,
11    pub forked_from: Option<String>,
12    pub query: String,
13}
14
15impl SessionMeta {
16    pub fn new(name: &str, query: &str) -> Self {
17        Self {
18            id: uuid::Uuid::new_v4().to_string(),
19            name: name.to_string(),
20            created_at: chrono::Utc::now().to_rfc3339(),
21            forked_from: None,
22            query: query.to_string(),
23        }
24    }
25
26    pub fn save(&self, sessions_dir: &std::path::Path) -> Result<(), FetchiumError> {
27        let dir = sessions_dir.join(&self.id);
28        std::fs::create_dir_all(&dir)?;
29        let content = serde_json::to_string_pretty(self)?;
30        std::fs::write(dir.join("session.json"), content)?;
31        Ok(())
32    }
33
34    pub fn load(sessions_dir: &std::path::Path, id: &str) -> Result<Self, FetchiumError> {
35        let content = std::fs::read_to_string(sessions_dir.join(id).join("session.json"))?;
36        Ok(serde_json::from_str(&content)?)
37    }
38}
39
40/// Fork an existing session to create a new branch.
41///
42/// Performs a deep copy of `session_id` directory, then updates metadata.
43pub fn fork_session(
44    sessions_dir: &std::path::Path,
45    session_id: &str,
46    new_name: &str,
47) -> Result<SessionMeta, FetchiumError> {
48    let source = sessions_dir.join(session_id);
49    if !source.exists() {
50        return Err(FetchiumError::Config(format!(
51            "Session '{session_id}' not found"
52        )));
53    }
54
55    let mut meta = SessionMeta::load(sessions_dir, session_id)?;
56    let new_id = uuid::Uuid::new_v4().to_string();
57    let dest = sessions_dir.join(&new_id);
58
59    copy_dir(&source, &dest)?;
60
61    meta.id = new_id;
62    meta.name = new_name.to_string();
63    meta.forked_from = Some(session_id.to_string());
64    meta.created_at = chrono::Utc::now().to_rfc3339();
65    meta.save(sessions_dir)?;
66
67    tracing::info!(name = new_name, from = session_id, "Session forked");
68    Ok(meta)
69}
70
71fn copy_dir(src: &std::path::Path, dst: &std::path::Path) -> Result<(), FetchiumError> {
72    std::fs::create_dir_all(dst)?;
73    for entry in std::fs::read_dir(src)? {
74        let entry = entry?;
75        let src_path = entry.path();
76        let dst_path = dst.join(entry.file_name());
77        if src_path.is_dir() {
78            copy_dir(&src_path, &dst_path)?;
79        } else {
80            std::fs::copy(&src_path, &dst_path)?;
81        }
82    }
83    Ok(())
84}