Skip to main content

lean_ctx/tools/
ctx_share.rs

1use serde::{Deserialize, Serialize};
2use std::path::PathBuf;
3
4#[derive(Serialize, Deserialize, Clone)]
5struct SharedContext {
6    from_agent: String,
7    to_agent: Option<String>,
8    files: Vec<SharedFile>,
9    message: Option<String>,
10    timestamp: String,
11}
12
13#[derive(Serialize, Deserialize, Clone)]
14struct SharedFile {
15    path: String,
16    content: String,
17    mode: String,
18    tokens: usize,
19}
20
21fn shared_dir(project_root: &str) -> PathBuf {
22    let hash = crate::core::project_hash::hash_project_root(project_root);
23    crate::core::data_dir::lean_ctx_data_dir()
24        .unwrap_or_else(|_| PathBuf::from("."))
25        .join("agents")
26        .join("shared")
27        .join(hash)
28}
29
30pub fn handle(
31    action: &str,
32    from_agent: Option<&str>,
33    to_agent: Option<&str>,
34    paths: Option<&str>,
35    message: Option<&str>,
36    cache: &crate::core::cache::SessionCache,
37    project_root: &str,
38) -> String {
39    match action {
40        "push" => handle_push(from_agent, to_agent, paths, message, cache, project_root),
41        "pull" => handle_pull(from_agent, project_root),
42        "list" => handle_list(project_root),
43        "clear" => handle_clear(from_agent, project_root),
44        _ => format!("Unknown action: {action}. Use: push, pull, list, clear"),
45    }
46}
47
48fn handle_push(
49    from_agent: Option<&str>,
50    to_agent: Option<&str>,
51    paths: Option<&str>,
52    message: Option<&str>,
53    cache: &crate::core::cache::SessionCache,
54    project_root: &str,
55) -> String {
56    let Some(from) = from_agent else {
57        return "Error: from_agent is required (register first via ctx_agent)".to_string();
58    };
59
60    let path_list: Vec<&str> = match paths {
61        Some(p) => p.split(',').map(str::trim).collect(),
62        None => return "Error: paths is required (comma-separated file paths)".to_string(),
63    };
64
65    let mut shared_files = Vec::new();
66    let mut not_found = Vec::new();
67
68    for path in &path_list {
69        if let Some(entry) = cache.get(path) {
70            shared_files.push(SharedFile {
71                path: entry.path.clone(),
72                content: entry.content.clone(),
73                mode: "full".to_string(),
74                tokens: entry.original_tokens,
75            });
76        } else {
77            not_found.push(*path);
78        }
79    }
80
81    if shared_files.is_empty() {
82        return format!(
83            "No cached files found to share. Files must be read first via ctx_read.\nNot found: {}",
84            not_found.join(", ")
85        );
86    }
87
88    let context = SharedContext {
89        from_agent: from.to_string(),
90        to_agent: to_agent.map(String::from),
91        files: shared_files.clone(),
92        message: message.map(String::from),
93        timestamp: chrono::Utc::now().to_rfc3339(),
94    };
95
96    let dir = shared_dir(project_root);
97    let _ = std::fs::create_dir_all(&dir);
98
99    let filename = format!(
100        "{}_{}.json",
101        from,
102        chrono::Utc::now().format("%Y%m%d_%H%M%S")
103    );
104    let path = dir.join(&filename);
105
106    match serde_json::to_string_pretty(&context) {
107        Ok(json) => {
108            if let Err(e) = std::fs::write(&path, json) {
109                return format!("Error writing shared context: {e}");
110            }
111        }
112        Err(e) => return format!("Error serializing shared context: {e}"),
113    }
114
115    let total_tokens: usize = shared_files.iter().map(|f| f.tokens).sum();
116    let mut result = format!(
117        "Shared {} files ({} tokens) from {from}",
118        shared_files.len(),
119        total_tokens
120    );
121
122    if let Some(target) = to_agent {
123        result.push_str(&format!(" → {target}"));
124    } else {
125        result.push_str(" → all agents (broadcast)");
126    }
127
128    if !not_found.is_empty() {
129        result.push_str(&format!(
130            "\nNot in cache (skipped): {}",
131            not_found.join(", ")
132        ));
133    }
134
135    result
136}
137
138fn handle_pull(agent_id: Option<&str>, project_root: &str) -> String {
139    let dir = shared_dir(project_root);
140    if !dir.exists() {
141        return "No shared contexts available.".to_string();
142    }
143
144    let my_id = agent_id.unwrap_or("anonymous");
145    let mut entries: Vec<SharedContext> = Vec::new();
146
147    if let Ok(readdir) = std::fs::read_dir(&dir) {
148        for entry in readdir.flatten() {
149            if let Ok(content) = std::fs::read_to_string(entry.path()) {
150                if let Ok(ctx) = serde_json::from_str::<SharedContext>(&content) {
151                    let is_for_me =
152                        ctx.to_agent.is_none() || ctx.to_agent.as_deref() == Some(my_id);
153                    let is_not_from_me = ctx.from_agent != my_id;
154
155                    if is_for_me && is_not_from_me {
156                        entries.push(ctx);
157                    }
158                }
159            }
160        }
161    }
162
163    if entries.is_empty() {
164        return "No shared contexts for you.".to_string();
165    }
166
167    entries.sort_by(|a, b| b.timestamp.cmp(&a.timestamp));
168
169    let mut out = format!("Shared contexts available ({}):\n", entries.len());
170    for ctx in &entries {
171        let file_list: Vec<&str> = ctx.files.iter().map(|f| f.path.as_str()).collect();
172        let total_tokens: usize = ctx.files.iter().map(|f| f.tokens).sum();
173        out.push_str(&format!(
174            "\n  From: {} ({})\n  Files: {} ({} tokens)\n  {}\n",
175            ctx.from_agent,
176            &ctx.timestamp[..19],
177            file_list.join(", "),
178            total_tokens,
179            ctx.message
180                .as_deref()
181                .map(|m| format!("Message: {m}"))
182                .unwrap_or_default(),
183        ));
184    }
185
186    let total_files: usize = entries.iter().map(|e| e.files.len()).sum();
187    out.push_str(&format!(
188        "\nTotal: {} contexts, {} files. Use ctx_read on pulled files to load them into your cache.",
189        entries.len(),
190        total_files
191    ));
192
193    out
194}
195
196fn handle_list(project_root: &str) -> String {
197    let dir = shared_dir(project_root);
198    if !dir.exists() {
199        return "No shared contexts.".to_string();
200    }
201
202    let mut count = 0;
203    let mut total_files = 0;
204    let mut out = String::from("Shared context store:\n");
205
206    if let Ok(readdir) = std::fs::read_dir(&dir) {
207        for entry in readdir.flatten() {
208            if let Ok(content) = std::fs::read_to_string(entry.path()) {
209                if let Ok(ctx) = serde_json::from_str::<SharedContext>(&content) {
210                    count += 1;
211                    total_files += ctx.files.len();
212                    let target = ctx.to_agent.as_deref().unwrap_or("broadcast");
213                    out.push_str(&format!(
214                        "  {} → {} ({} files, {})\n",
215                        ctx.from_agent,
216                        target,
217                        ctx.files.len(),
218                        &ctx.timestamp[..19]
219                    ));
220                }
221            }
222        }
223    }
224
225    if count == 0 {
226        return "No shared contexts.".to_string();
227    }
228
229    out.push_str(&format!("\nTotal: {count} shares, {total_files} files"));
230    out
231}
232
233fn handle_clear(agent_id: Option<&str>, project_root: &str) -> String {
234    let dir = shared_dir(project_root);
235    if !dir.exists() {
236        return "Nothing to clear.".to_string();
237    }
238
239    let my_id = agent_id.unwrap_or("anonymous");
240    let mut removed = 0;
241
242    if let Ok(readdir) = std::fs::read_dir(&dir) {
243        for entry in readdir.flatten() {
244            if let Ok(content) = std::fs::read_to_string(entry.path()) {
245                if let Ok(ctx) = serde_json::from_str::<SharedContext>(&content) {
246                    if ctx.from_agent == my_id {
247                        let _ = std::fs::remove_file(entry.path());
248                        removed += 1;
249                    }
250                }
251            }
252        }
253    }
254
255    format!("Cleared {removed} shared context(s) from {my_id}")
256}