marqant 1.0.0

Quantum-compressed markdown format for AI consumption with 90% token reduction
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
//! # Smart Log Summarization
//!
//! AI-friendly log analysis that surfaces what matters and filters noise.
//!
//! ## Philosophy
//!
//! Logs are 90% repetitive noise. This module uses marqant's compression
//! intelligence to find patterns and novelty detection to surface anomalies.
//!
//! ## Usage
//!
//! ```bash
//! tail -100 app.log | mq tail
//! mq tail -n 1000 app.log
//! tail -f app.log | mq tail --stream
//! ```

use crate::novelty::{NoveltyClass, NoveltyTracker};
use crate::semantic::{SemanticToken, SemanticUnit};
use std::collections::HashMap;

/// Configuration for log summarization
#[derive(Debug, Clone)]
pub struct SummarizerConfig {
    /// Minimum novelty threshold (0.0-1.0)
    pub novelty_threshold: f32,

    /// Show background noise stats
    pub show_noise: bool,

    /// Maximum lines to show per category
    pub max_per_category: usize,

    /// Use emojis in output
    pub use_emojis: bool,
}

impl Default for SummarizerConfig {
    fn default() -> Self {
        Self {
            novelty_threshold: 0.1,
            show_noise: true,
            max_per_category: 10,
            use_emojis: true,
        }
    }
}

/// A categorized log entry
#[derive(Debug, Clone)]
pub struct LogEntry {
    /// Original log line
    pub line: String,

    /// Pattern signature (for grouping similar lines)
    pub pattern: String,

    /// Novelty score
    pub novelty: f32,

    /// Classification
    pub class: NoveltyClass,

    /// Occurrence count
    pub count: usize,
}

/// Summary of analyzed logs
#[derive(Debug)]
pub struct LogSummary {
    /// Total lines analyzed
    pub total_lines: usize,

    /// Revolutionary patterns (never seen before)
    pub revolutionary: Vec<LogEntry>,

    /// Fresh/interesting patterns
    pub important: Vec<LogEntry>,

    /// Familiar patterns
    pub familiar: Vec<LogEntry>,

    /// Background noise (filtered)
    pub noise: Vec<(String, usize)>,

    /// Total lines filtered as noise
    pub noise_count: usize,
}

/// Smart log summarizer using marqant compression + novelty detection
pub struct LogSummarizer {
    /// Novelty tracker
    novelty_tracker: NoveltyTracker,

    /// Pattern frequency map
    pattern_counts: HashMap<String, usize>,

    /// Configuration (reserved for future use)
    _config: SummarizerConfig,
}

impl LogSummarizer {
    /// Create a new log summarizer
    pub fn new(config: SummarizerConfig) -> Self {
        Self {
            novelty_tracker: NoveltyTracker::new(),
            pattern_counts: HashMap::new(),
            _config: config,
        }
    }

    /// Analyze log lines and generate summary
    pub fn summarize(&mut self, lines: &[String]) -> LogSummary {
        let mut revolutionary = Vec::new();
        let mut important = Vec::new();
        let mut familiar = Vec::new();
        let mut noise = Vec::new();
        let mut noise_count = 0;

        // Analyze each line
        for line in lines {
            let entry = self.analyze_line(line);

            match entry.class {
                NoveltyClass::Revolutionary => revolutionary.push(entry),
                NoveltyClass::Fresh | NoveltyClass::Interesting => important.push(entry),
                NoveltyClass::Familiar => familiar.push(entry),
                NoveltyClass::Stale | NoveltyClass::BackgroundNoise => {
                    noise.push((entry.pattern, entry.count));
                    noise_count += entry.count;
                }
            }
        }

        // Deduplicate and sort by novelty
        revolutionary.sort_by(|a, b| b.novelty.partial_cmp(&a.novelty).unwrap());
        important.sort_by(|a, b| b.novelty.partial_cmp(&a.novelty).unwrap());
        familiar.sort_by(|a, b| b.novelty.partial_cmp(&a.novelty).unwrap());

        // Deduplicate by pattern
        revolutionary = Self::deduplicate_entries(revolutionary);
        important = Self::deduplicate_entries(important);
        familiar = Self::deduplicate_entries(familiar);

        // Aggregate noise patterns
        let noise = Self::aggregate_noise_patterns(noise);

        LogSummary {
            total_lines: lines.len(),
            revolutionary,
            important,
            familiar,
            noise,
            noise_count,
        }
    }

    /// Analyze a single log line
    fn analyze_line(&mut self, line: &str) -> LogEntry {
        // Extract pattern (simplified: ignore timestamps, IPs, numbers)
        let pattern = self.extract_pattern(line);

        // Track pattern frequency
        *self.pattern_counts.entry(pattern.clone()).or_insert(0) += 1;
        let count = self.pattern_counts[&pattern];

        // Create semantic unit for novelty detection
        let semantic_unit = self.line_to_semantic_unit(line);

        // Calculate novelty
        let novelty_score = self.novelty_tracker.calculate_novelty(&[semantic_unit]);

        LogEntry {
            line: line.to_string(),
            pattern,
            novelty: novelty_score.value,
            class: novelty_score.classification,
            count,
        }
    }

    /// Extract pattern from log line (remove variable parts)
    fn extract_pattern(&self, line: &str) -> String {
        let mut pattern = line.to_string();

        // Remove timestamps (ISO 8601, syslog, etc.)
        pattern = regex::Regex::new(r"\d{4}-\d{2}-\d{2}[T\s]\d{2}:\d{2}:\d{2}")
            .unwrap()
            .replace_all(&pattern, "<TIMESTAMP>")
            .to_string();

        // Remove IPs
        pattern = regex::Regex::new(r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}")
            .unwrap()
            .replace_all(&pattern, "<IP>")
            .to_string();

        // Remove numbers (but keep log levels)
        pattern = regex::Regex::new(r"\b\d+\b")
            .unwrap()
            .replace_all(&pattern, "<NUM>")
            .to_string();

        // Remove UUIDs
        pattern =
            regex::Regex::new(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")
                .unwrap()
                .replace_all(&pattern, "<UUID>")
                .to_string();

        pattern
    }

    /// Convert log line to semantic unit for novelty tracking
    fn line_to_semantic_unit(&self, line: &str) -> SemanticUnit {
        // Analyze log line and extract semantic meaning
        let mut tokens = Vec::new();
        let line_lower = line.to_lowercase();

        // Detect log level/severity
        if line_lower.contains("error") || line_lower.contains("fatal") {
            tokens.push(SemanticToken::EmotionFrustrated);
        } else if line_lower.contains("warn") {
            tokens.push(SemanticToken::QualifierMedium);
        } else if line_lower.contains("info") {
            tokens.push(SemanticToken::QualifierLow);
        }

        // Detect process states
        if line_lower.contains("start") || line_lower.contains("begin") {
            tokens.push(SemanticToken::ProcessActive);
        } else if line_lower.contains("complete") || line_lower.contains("success") {
            tokens.push(SemanticToken::ProcessComplete);
        }

        // Detect system entities
        if line_lower.contains("database") || line_lower.contains("db") {
            tokens.push(SemanticToken::EntitySystem);
        }

        // If no tokens detected, use a generic token
        if tokens.is_empty() {
            tokens.push(SemanticToken::ContextProgramming);
        }

        // Calculate intensity based on log level
        let intensity = if line_lower.contains("error") || line_lower.contains("fatal") {
            1.0
        } else if line_lower.contains("warn") {
            0.7
        } else {
            0.3
        };

        SemanticUnit {
            tokens,
            metadata: HashMap::new(),
            intensity,
        }
    }

    /// Deduplicate entries by pattern
    fn deduplicate_entries(entries: Vec<LogEntry>) -> Vec<LogEntry> {
        let mut seen = HashMap::new();
        let mut result = Vec::new();

        for entry in entries {
            if !seen.contains_key(&entry.pattern) {
                seen.insert(entry.pattern.clone(), true);
                result.push(entry);
            }
        }

        result
    }

    /// Aggregate noise patterns and count occurrences
    fn aggregate_noise_patterns(noise: Vec<(String, usize)>) -> Vec<(String, usize)> {
        let mut aggregated = HashMap::new();

        for (pattern, count) in noise {
            *aggregated.entry(pattern).or_insert(0) += count;
        }

        let mut result: Vec<_> = aggregated.into_iter().collect();
        result.sort_by(|a, b| b.1.cmp(&a.1)); // Sort by count descending

        result
    }
}

impl LogSummary {
    /// Format summary as human-readable text
    pub fn format(&self, config: &SummarizerConfig) -> String {
        let mut output = String::new();

        // Header
        output.push_str(&format!(
            "📊 Log Summary ({} lines analyzed)\n",
            self.total_lines
        ));
        output.push_str("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n");

        // Revolutionary patterns
        if !self.revolutionary.is_empty() {
            let emoji = if config.use_emojis { "💎 " } else { "" };
            output.push_str(&format!(
                "{}NOVEL PATTERNS ({})\n",
                emoji,
                self.revolutionary.len()
            ));

            for entry in self.revolutionary.iter().take(config.max_per_category) {
                output.push_str(&format!("{}\n", entry.line));
            }
            output.push('\n');
        }

        // Important patterns
        if !self.important.is_empty() {
            let emoji = if config.use_emojis { "🌟 " } else { "" };
            output.push_str(&format!("{}IMPORTANT ({})\n", emoji, self.important.len()));

            for entry in self.important.iter().take(config.max_per_category) {
                output.push_str(&format!("{}\n", entry.line));
            }
            output.push('\n');
        }

        // Familiar patterns
        if !self.familiar.is_empty() && self.familiar.len() < 20 {
            let emoji = if config.use_emojis { "📝 " } else { "" };
            output.push_str(&format!("{}FAMILIAR ({})\n", emoji, self.familiar.len()));

            for entry in self.familiar.iter().take(config.max_per_category) {
                output.push_str(&format!(
                    "{} (seen {} times)\n",
                    entry.line, entry.count
                ));
            }
            output.push('\n');
        }

        // Background noise summary
        if config.show_noise && self.noise_count > 0 {
            let emoji = if config.use_emojis { "💤 " } else { "" };
            output.push_str(&format!(
                "{}BACKGROUND NOISE (filtered {} lines)\n",
                emoji, self.noise_count
            ));

            // Show top noise patterns
            for (pattern, count) in self.noise.iter().take(5) {
                let truncated = if pattern.len() > 80 {
                    format!("{}...", &pattern[..77])
                } else {
                    pattern.clone()
                };
                output.push_str(&format!("{}: {} occurrences\n", truncated, count));
            }
        }

        output
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_pattern_extraction() {
        let config = SummarizerConfig::default();
        let summarizer = LogSummarizer::new(config);

        let line1 = "2024-01-15 10:30:45 ERROR Connection timeout to 192.168.1.100";
        let line2 = "2024-01-15 10:31:22 ERROR Connection timeout to 192.168.1.200";

        let pattern1 = summarizer.extract_pattern(line1);
        let pattern2 = summarizer.extract_pattern(line2);

        // Patterns should be identical (variables removed)
        assert_eq!(pattern1, pattern2);
        assert!(pattern1.contains("<TIMESTAMP>"));
        assert!(pattern1.contains("<IP>"));
    }

    #[test]
    fn test_novelty_detection() {
        let config = SummarizerConfig::default();
        let mut summarizer = LogSummarizer::new(config);

        // Add many repeated lines to trigger familiar/noise classification
        let mut lines = vec![];
        for _ in 0..10 {
            lines.push("INFO: Server started successfully".to_string());
        }
        lines.push("ERROR: Database connection failed".to_string());

        let summary = summarizer.summarize(&lines);

        // Should have novel patterns
        assert!(summary.revolutionary.len() > 0 || summary.important.len() > 0);

        // Should detect repetition with many occurrences
        // After 10 repetitions, patterns should be familiar or noise
        assert!(
            summary.noise_count > 0 || summary.familiar.len() > 0,
            "Expected repetition detection. Revolutionary: {}, Important: {}, Familiar: {}, Noise: {}",
            summary.revolutionary.len(),
            summary.important.len(),
            summary.familiar.len(),
            summary.noise_count
        );
    }
}