octomind 0.25.0

Session-based AI development assistant with conversational codebase interaction, multimodal vision support, built-in MCP tools, and multi-provider AI integration
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
// Copyright 2026 Muvon Un Limited
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Smart text summarization for context management

use crate::session::Message;
use anyhow::Result;

/// Smart summarizer for conversation context
pub struct SmartSummarizer;

impl SmartSummarizer {
	/// Create a new smart summarizer
	pub fn new() -> Self {
		Self
	}

	/// Summarize a list of messages intelligently
	/// Preserves technical context, file modifications, and key decisions
	pub fn summarize_messages(&self, messages: &[Message]) -> Result<String> {
		if messages.is_empty() {
			return Ok("No messages to summarize.".to_string());
		}

		// Extract and categorize content from messages
		let mut conversation_flow = Vec::new();
		let mut technical_context = Vec::new();
		let mut file_modifications = Vec::new();
		let mut tool_usage = Vec::new();
		let mut key_decisions = Vec::new();

		for msg in messages {
			match msg.role.as_str() {
				"system" => {
					// Skip system messages - they're preserved separately
					continue;
				}
				"user" => {
					conversation_flow
						.push(format!("User: {}", self.extract_key_points(&msg.content)));

					// Extract technical keywords and context
					if self.contains_technical_content(&msg.content) {
						technical_context.push(self.extract_technical_info(&msg.content));
					}
				}
				"assistant" => {
					conversation_flow.push(format!(
						"Assistant: {}",
						self.extract_key_points(&msg.content)
					));

					// Extract file modification mentions
					if self.contains_file_modifications(&msg.content) {
						file_modifications.push(self.extract_file_info(&msg.content));
					}

					// Extract decisions and solutions
					if self.contains_decisions(&msg.content) {
						key_decisions.push(self.extract_decisions(&msg.content));
					}
				}
				"tool" => {
					// Preserve tool results as they contain important context
					tool_usage.push(self.extract_tool_summary(&msg.content));
				}
				_ => {
					conversation_flow.push(format!(
						"{}: {}",
						msg.role,
						self.extract_key_points(&msg.content)
					));
				}
			}
		}

		// Build comprehensive summary
		let mut summary_parts = Vec::new();

		// Add conversation overview
		if !conversation_flow.is_empty() {
			summary_parts.push("Conversation Overview:".to_string());
			// Take key conversation points (first, last, and some middle points)
			let points_to_include = std::cmp::min(5, conversation_flow.len());
			for (i, point) in conversation_flow.iter().take(points_to_include).enumerate() {
				summary_parts.push(format!("{}. {}", i + 1, point));
			}
		}

		// Add technical context
		if !technical_context.is_empty() {
			summary_parts.push("\nTechnical Context:".to_string());
			for (i, context) in technical_context.iter().take(3).enumerate() {
				summary_parts.push(format!("{}. {}", i + 1, context));
			}
		}

		// Add file modifications
		if !file_modifications.is_empty() {
			summary_parts.push("\nFile Modifications:".to_string());
			for (i, modification) in file_modifications.iter().take(3).enumerate() {
				summary_parts.push(format!("{}. {}", i + 1, modification));
			}
		}

		// Add key decisions
		if !key_decisions.is_empty() {
			summary_parts.push("\nKey Decisions:".to_string());
			for (i, decision) in key_decisions.iter().take(3).enumerate() {
				summary_parts.push(format!("{}. {}", i + 1, decision));
			}
		}

		// Add tool usage
		if !tool_usage.is_empty() {
			summary_parts.push("\nTool Usage:".to_string());
			summary_parts.push(format!(
				"Used {} development tools: {}",
				tool_usage.len(),
				tool_usage.join(", ")
			));
		}

		Ok(summary_parts.join("\n"))
	}

	/// Check if content contains technical information
	fn contains_technical_content(&self, content: &str) -> bool {
		let technical_keywords = [
			"function",
			"class",
			"method",
			"variable",
			"import",
			"export",
			"struct",
			"enum",
			"trait",
			"impl",
			"mod",
			"use",
			"pub",
			"async",
			"await",
			"Result",
			"Error",
			"Ok",
			"Err",
			"config",
			"configuration",
			"setup",
			"install",
			"deploy",
			"api",
			"endpoint",
			"request",
			"response",
			"http",
			"json",
			"database",
			"query",
			"sql",
			"table",
			"index",
			"test",
			"testing",
			"unit test",
			"integration",
			"bug",
			"fix",
			"issue",
			"error",
			"exception",
			"refactor",
			"optimize",
			"performance",
			"memory",
			"security",
			"authentication",
			"authorization",
			"docker",
			"kubernetes",
			"deployment",
			"ci/cd",
		];

		let content_lower = content.to_lowercase();
		technical_keywords
			.iter()
			.any(|keyword| content_lower.contains(keyword))
	}

	/// Check if content contains file modification information
	fn contains_file_modifications(&self, content: &str) -> bool {
		let file_keywords = [
			"created",
			"modified",
			"updated",
			"changed",
			"edited",
			"added",
			"removed",
			"deleted",
			"renamed",
			"moved",
			"file",
			"directory",
			"folder",
			"path",
			".rs",
			".toml",
			".json",
			".yaml",
			".md",
			".txt",
			"src/",
			"tests/",
			"docs/",
			"examples/",
		];

		let content_lower = content.to_lowercase();
		file_keywords
			.iter()
			.any(|keyword| content_lower.contains(keyword))
	}

	/// Check if content contains decisions or solutions
	fn contains_decisions(&self, content: &str) -> bool {
		let decision_keywords = [
			"decided",
			"choose",
			"selected",
			"option",
			"approach",
			"solution",
			"resolved",
			"implemented",
			"strategy",
			"recommend",
			"suggest",
			"best practice",
			"should",
			"will use",
			"going with",
			"final",
			"conclusion",
		];

		let content_lower = content.to_lowercase();
		decision_keywords
			.iter()
			.any(|keyword| content_lower.contains(keyword))
	}

	/// Extract key points from content (first sentence or up to 150 characters)
	fn extract_key_points(&self, content: &str) -> String {
		let sentences: Vec<&str> = content.split('.').collect();
		if let Some(first_sentence) = sentences.first() {
			if first_sentence.chars().count() <= 150 {
				first_sentence.trim().to_string()
			} else {
				let truncated: String = first_sentence.chars().take(147).collect();
				format!("{}...", truncated.trim())
			}
		} else if content.chars().count() <= 150 {
			content.trim().to_string()
		} else {
			let truncated: String = content.chars().take(147).collect();
			format!("{}...", truncated.trim())
		}
	}

	/// Extract technical information from content
	fn extract_technical_info(&self, content: &str) -> String {
		// Look for code-related patterns and technical terms
		let lines: Vec<&str> = content.lines().collect();
		for line in &lines {
			if line.contains("```")
				|| line.contains("fn ")
				|| line.contains("struct ")
				|| line.contains("impl ")
				|| line.contains("use ")
			{
				return self.extract_key_points(line);
			}
		}
		self.extract_key_points(content)
	}

	/// Extract file information from modification content
	fn extract_file_info(&self, content: &str) -> String {
		// Look for file paths and modification types
		let words: Vec<&str> = content.split_whitespace().collect();
		let mut file_info = Vec::new();

		for window in words.windows(3) {
			if let [action, _, file] = window {
				if ["created", "modified", "updated", "added", "removed"].contains(action)
					&& (file.contains('.') || file.contains('/'))
				{
					file_info.push(format!("{} {}", action, file));
					break;
				}
			}
		}

		if file_info.is_empty() {
			self.extract_key_points(content)
		} else {
			file_info.join(", ")
		}
	}

	/// Extract decisions from content
	fn extract_decisions(&self, content: &str) -> String {
		let sentences: Vec<&str> = content.split('.').collect();
		for sentence in &sentences {
			if self.contains_decisions(sentence) {
				return self.extract_key_points(sentence);
			}
		}
		self.extract_key_points(content)
	}

	/// Extract tool usage summary
	fn extract_tool_summary(&self, content: &str) -> String {
		// Extract tool name or action from tool result
		// Use char-based truncation to avoid UTF-8 boundary issues
		if content.chars().count() > 50 {
			let truncated: String = content.chars().take(47).collect();
			format!("tool execution ({}...)", truncated)
		} else {
			format!("tool execution ({})", content)
		}
	}
}

impl Default for SmartSummarizer {
	fn default() -> Self {
		Self::new()
	}
}

#[cfg(test)]
mod tests {
	use super::*;
	use std::time::{SystemTime, UNIX_EPOCH};

	#[test]
	fn test_summarize_empty_messages() {
		let summarizer = SmartSummarizer::new();
		let result = summarizer.summarize_messages(&[]).unwrap();
		assert_eq!(result, "No messages to summarize.");
	}

	#[test]
	fn test_contains_technical_content() {
		let summarizer = SmartSummarizer::new();

		assert!(summarizer.contains_technical_content("Let's create a new function"));
		assert!(summarizer.contains_technical_content("Update the config file"));
		assert!(summarizer.contains_technical_content("Fix the API endpoint"));
		assert!(!summarizer.contains_technical_content("Hello, how are you?"));
	}

	#[test]
	fn test_contains_file_modifications() {
		let summarizer = SmartSummarizer::new();

		assert!(summarizer.contains_file_modifications("I created a new file"));
		assert!(summarizer.contains_file_modifications("Modified src/main.rs"));
		assert!(summarizer.contains_file_modifications("Updated the .toml configuration"));
		assert!(!summarizer.contains_file_modifications("Just talking about code"));
	}

	#[test]
	fn test_summarize_simple_conversation() {
		let summarizer = SmartSummarizer::new();

		let messages = vec![
			Message {
				role: "user".to_string(),
				content: "Can you help me create a function to parse JSON?".to_string(),
				timestamp: SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs(),
				cached: false,
				cache_ttl: None,
				tool_call_id: None,
				name: None,
				tool_calls: None,
				images: None,
				videos: None,
				thinking: None,
				id: None,
			},
		Message {
			role: "assistant".to_string(),
			content: "I'll help you create a JSON parsing function. Let me create a new file for this.".to_string(),
			timestamp: SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs(),
			cached: false,
			cache_ttl: None,
			tool_call_id: None,
			name: None,
			tool_calls: None,
			images: None,
			videos: None,
			thinking: None,
			id: None,
		},
		];

		let result = summarizer.summarize_messages(&messages).unwrap();
		assert!(result.contains("function"));
		assert!(result.contains("JSON") || result.contains("json"));
	}
}