securegit 0.8.5

Zero-trust git replacement with 12 built-in security scanners, LLM redteam bridge, universal undo, durable backups, and a 50-tool MCP server
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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
//! SQLite-backed token usage tracking for compact output analytics.
//!
//! Records per-command token savings so users can see how much compact output
//! reduces context-window consumption over time.

use std::path::PathBuf;
use std::time::Instant;

use anyhow::Result;
use rusqlite::{params, Connection};

use crate::cli::compact::{estimate_tokens, format_tokens};

// ── Database ────────────────────────────────────────────────────────────────

/// Return the path to the tracking database.
///
/// `~/.local/share/securegit/tracking.db` (Linux/macOS via `dirs::data_dir`).
fn db_path() -> Result<PathBuf> {
    let base =
        dirs::data_dir().ok_or_else(|| anyhow::anyhow!("could not determine data directory"))?;
    Ok(base.join("securegit").join("tracking.db"))
}

/// Open (or create) the tracking database and ensure the schema exists.
fn open_db() -> Result<Connection> {
    let path = db_path()?;
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    let conn = Connection::open(&path)?;

    conn.execute_batch(
        "CREATE TABLE IF NOT EXISTS command_history (
            id            INTEGER PRIMARY KEY AUTOINCREMENT,
            timestamp     TEXT    NOT NULL DEFAULT (datetime('now')),
            command       TEXT    NOT NULL,
            input_tokens  INTEGER NOT NULL,
            output_tokens INTEGER NOT NULL,
            saved_tokens  INTEGER NOT NULL,
            savings_pct   REAL    NOT NULL,
            duration_ms   INTEGER NOT NULL
        );

        CREATE INDEX IF NOT EXISTS idx_ch_timestamp ON command_history(timestamp);
        CREATE INDEX IF NOT EXISTS idx_ch_command   ON command_history(command);",
    )?;

    Ok(conn)
}

// ── Recording ───────────────────────────────────────────────────────────────

/// Record a single command's token usage.
///
/// `normal_output` is the full (uncompressed) output, `compact_output` is the
/// token-optimised variant.  Savings are computed from the difference.
///
/// Errors are silently swallowed -- tracking must never fail the main command.
pub fn record(command: &str, normal_output: &str, compact_output: &str, duration_ms: u64) {
    let _ = record_inner(command, normal_output, compact_output, duration_ms);
}

fn record_inner(
    command: &str,
    normal_output: &str,
    compact_output: &str,
    duration_ms: u64,
) -> Result<()> {
    let input_tokens = estimate_tokens(normal_output);
    let output_tokens = estimate_tokens(compact_output);
    let saved_tokens = input_tokens.saturating_sub(output_tokens);
    let savings_pct = if input_tokens > 0 {
        (saved_tokens as f64 / input_tokens as f64) * 100.0
    } else {
        0.0
    };

    let conn = open_db()?;

    conn.execute(
        "INSERT INTO command_history (command, input_tokens, output_tokens, saved_tokens, savings_pct, duration_ms)
         VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
        params![command, input_tokens, output_tokens, saved_tokens, savings_pct, duration_ms as i64],
    )?;

    // Auto-clean entries older than 90 days.
    conn.execute(
        "DELETE FROM command_history WHERE timestamp < datetime('now', '-90 days')",
        [],
    )?;

    Ok(())
}

// ── Timer ───────────────────────────────────────────────────────────────────

/// A lightweight timer for measuring command duration.
pub struct Timer {
    start: Instant,
    command: String,
}

impl Timer {
    /// Start a new timer for the given command name.
    pub fn start(command: impl Into<String>) -> Self {
        Self {
            start: Instant::now(),
            command: command.into(),
        }
    }

    /// Elapsed time in milliseconds since the timer was started.
    pub fn elapsed_ms(&self) -> u64 {
        self.start.elapsed().as_millis() as u64
    }

    /// Convenience: record token usage using this timer's elapsed time.
    ///
    /// Silently ignores errors.
    pub fn record(&self, normal_output: &str, compact_output: &str) {
        record(
            &self.command,
            normal_output,
            compact_output,
            self.elapsed_ms(),
        );
    }
}

// ── Summary Types ───────────────────────────────────────────────────────────

/// Aggregate token-savings statistics.
pub struct GainSummary {
    pub total_commands: usize,
    pub total_input_tokens: usize,
    pub total_output_tokens: usize,
    pub total_saved_tokens: usize,
    pub efficiency_pct: f64,
    pub by_command: Vec<CommandStats>,
}

/// Per-command aggregate statistics.
pub struct CommandStats {
    pub command: String,
    pub count: usize,
    pub saved_tokens: usize,
    pub avg_savings_pct: f64,
}

/// A single history entry.
pub struct HistoryEntry {
    pub timestamp: String,
    pub command: String,
    pub input_tokens: usize,
    pub output_tokens: usize,
    pub saved_tokens: usize,
    pub savings_pct: f64,
    pub duration_ms: u64,
}

// ── Queries ─────────────────────────────────────────────────────────────────

/// Build an aggregate summary of all recorded token savings.
pub fn get_summary() -> Result<GainSummary> {
    let conn = open_db()?;

    // Totals
    let (total_commands, total_input, total_output, total_saved): (usize, usize, usize, usize) =
        conn.query_row(
            "SELECT COUNT(*),
                    COALESCE(SUM(input_tokens), 0),
                    COALESCE(SUM(output_tokens), 0),
                    COALESCE(SUM(saved_tokens), 0)
             FROM command_history",
            [],
            |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)),
        )?;

    let efficiency_pct = if total_input > 0 {
        (total_saved as f64 / total_input as f64) * 100.0
    } else {
        0.0
    };

    // Top 10 commands by total saved tokens
    let mut stmt = conn.prepare(
        "SELECT command,
                COUNT(*) AS cnt,
                SUM(saved_tokens) AS saved,
                AVG(savings_pct)  AS avg_pct
         FROM command_history
         GROUP BY command
         ORDER BY saved DESC
         LIMIT 10",
    )?;

    let by_command = stmt
        .query_map([], |row| {
            Ok(CommandStats {
                command: row.get(0)?,
                count: row.get(1)?,
                saved_tokens: row.get(2)?,
                avg_savings_pct: row.get(3)?,
            })
        })?
        .filter_map(|r| r.ok())
        .collect();

    Ok(GainSummary {
        total_commands,
        total_input_tokens: total_input,
        total_output_tokens: total_output,
        total_saved_tokens: total_saved,
        efficiency_pct,
        by_command,
    })
}

/// Return the most recent history entries.
pub fn get_history(limit: usize) -> Result<Vec<HistoryEntry>> {
    let conn = open_db()?;

    let mut stmt = conn.prepare(
        "SELECT timestamp, command, input_tokens, output_tokens,
                saved_tokens, savings_pct, duration_ms
         FROM command_history
         ORDER BY id DESC
         LIMIT ?1",
    )?;

    let entries = stmt
        .query_map(params![limit], |row| {
            Ok(HistoryEntry {
                timestamp: row.get(0)?,
                command: row.get(1)?,
                input_tokens: row.get(2)?,
                output_tokens: row.get(3)?,
                saved_tokens: row.get(4)?,
                savings_pct: row.get(5)?,
                duration_ms: row.get::<_, i64>(6)? as u64,
            })
        })?
        .filter_map(|r| r.ok())
        .collect();

    Ok(entries)
}

// ── Display ─────────────────────────────────────────────────────────────────

/// Print a formatted summary of token savings to stdout.
pub fn display_summary(summary: &GainSummary) {
    println!("Token Savings Summary");
    println!("=====================");
    println!();
    println!("  Total commands:   {}", summary.total_commands);
    println!(
        "  Input tokens:     {}",
        format_tokens(summary.total_input_tokens)
    );
    println!(
        "  Output tokens:    {}",
        format_tokens(summary.total_output_tokens)
    );
    println!(
        "  Tokens saved:     {}",
        format_tokens(summary.total_saved_tokens)
    );
    println!("  Efficiency:       {:.1}%", summary.efficiency_pct);

    if !summary.by_command.is_empty() {
        println!();
        println!("  Top Commands by Savings");
        println!(
            "  {:<20} {:>6} {:>10} {:>8}",
            "Command", "Count", "Saved", "Avg %"
        );
        println!(
            "  {:<20} {:>6} {:>10} {:>8}",
            "-------", "-----", "-----", "-----"
        );
        for cs in &summary.by_command {
            println!(
                "  {:<20} {:>6} {:>10} {:>7.1}%",
                cs.command,
                cs.count,
                format_tokens(cs.saved_tokens),
                cs.avg_savings_pct,
            );
        }
    }
}

/// Print a formatted history table to stdout.
pub fn display_history(entries: &[HistoryEntry]) {
    if entries.is_empty() {
        println!("No tracking history found.");
        return;
    }

    println!(
        "{:<20} {:<16} {:>8} {:>8} {:>8} {:>7} {:>7}",
        "Timestamp", "Command", "Input", "Output", "Saved", "Pct", "ms"
    );
    println!(
        "{:<20} {:<16} {:>8} {:>8} {:>8} {:>7} {:>7}",
        "---------", "-------", "-----", "------", "-----", "---", "--"
    );

    for e in entries {
        println!(
            "{:<20} {:<16} {:>8} {:>8} {:>8} {:>6.1}% {:>7}",
            e.timestamp,
            e.command,
            format_tokens(e.input_tokens),
            format_tokens(e.output_tokens),
            format_tokens(e.saved_tokens),
            e.savings_pct,
            e.duration_ms,
        );
    }
}

// ── Tests ───────────────────────────────────────────────────────────────────

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

    #[test]
    fn test_timer_start_and_elapsed() {
        let timer = Timer::start("test-cmd");
        std::thread::sleep(std::time::Duration::from_millis(10));
        let elapsed = timer.elapsed_ms();
        assert!(
            elapsed > 0,
            "elapsed_ms should be > 0 after sleeping, got {elapsed}"
        );
    }

    #[test]
    fn test_estimate_savings() {
        // record_inner computes savings internally.  We replicate the logic here
        // to test the pure calculation without touching the DB.
        let normal = "a]".repeat(100); // 200 bytes => 50 tokens
        let compact = "a".repeat(40); // 40 bytes  => 10 tokens

        let input_tokens = estimate_tokens(&normal);
        let output_tokens = estimate_tokens(&compact);
        let saved = input_tokens.saturating_sub(output_tokens);
        let pct = if input_tokens > 0 {
            (saved as f64 / input_tokens as f64) * 100.0
        } else {
            0.0
        };

        assert_eq!(input_tokens, 50);
        assert_eq!(output_tokens, 10);
        assert_eq!(saved, 40);
        assert!(
            (pct - 80.0).abs() < 0.01,
            "Expected ~80% savings, got {pct}"
        );

        // Edge case: identical output => 0 savings
        let same = "hello";
        let inp = estimate_tokens(same);
        let out = estimate_tokens(same);
        assert_eq!(inp.saturating_sub(out), 0);

        // Edge case: empty input => 0%
        let empty_inp = estimate_tokens("");
        let empty_pct = if empty_inp > 0 { 100.0 } else { 0.0 };
        assert_eq!(empty_pct, 0.0);
    }

    #[test]
    fn test_record_and_retrieve() {
        // Record a command with a unique name so we can find it
        let unique = format!(
            "test-record-{}",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        );

        record(&unique, "normal output text here", "compact", 42);

        // Retrieve recent history and find our entry
        let history = get_history(100).expect("get_history should succeed");
        let found = history.iter().find(|e| e.command == unique);
        assert!(found.is_some(), "recorded command should appear in history");

        let entry = found.unwrap();
        assert_eq!(entry.duration_ms, 42);
        assert!(entry.input_tokens > 0);
        assert!(entry.output_tokens > 0);
        assert!(entry.saved_tokens > 0);
    }

    #[test]
    fn test_get_summary() {
        // Record a few commands to ensure aggregation works
        let prefix = format!(
            "test-summary-{}",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        );

        record(&prefix, "aaaa bbbb cccc", "ab", 10);
        record(&prefix, "dddd eeee ffff", "de", 20);
        record(&prefix, "gggg hhhh iiii", "gh", 30);

        let summary = get_summary().expect("get_summary should succeed");
        // We added 3 commands, but there may be others from previous tests
        assert!(
            summary.total_commands >= 3,
            "should have at least 3 commands, got {}",
            summary.total_commands
        );
        assert!(summary.total_input_tokens > 0);
        assert!(summary.total_saved_tokens > 0);
        assert!(summary.efficiency_pct > 0.0);
        // by_command should have at least one entry
        assert!(!summary.by_command.is_empty());
    }

    #[test]
    fn test_get_history_limit() {
        // Record several commands
        for i in 0..5 {
            record(
                &format!("test-limit-{i}"),
                "some long normal output text",
                "short",
                i as u64,
            );
        }

        // Request only 2
        let history = get_history(2).expect("get_history should succeed");
        assert!(
            history.len() <= 2,
            "limit=2 should return at most 2 entries, got {}",
            history.len()
        );
    }

    #[test]
    fn test_display_summary_no_panic() {
        // Empty summary
        let empty = GainSummary {
            total_commands: 0,
            total_input_tokens: 0,
            total_output_tokens: 0,
            total_saved_tokens: 0,
            efficiency_pct: 0.0,
            by_command: vec![],
        };
        display_summary(&empty); // should not panic

        // Summary with data
        let with_data = GainSummary {
            total_commands: 100,
            total_input_tokens: 50_000,
            total_output_tokens: 10_000,
            total_saved_tokens: 40_000,
            efficiency_pct: 80.0,
            by_command: vec![
                CommandStats {
                    command: "status".into(),
                    count: 50,
                    saved_tokens: 20_000,
                    avg_savings_pct: 75.0,
                },
                CommandStats {
                    command: "diff".into(),
                    count: 30,
                    saved_tokens: 15_000,
                    avg_savings_pct: 85.0,
                },
            ],
        };
        display_summary(&with_data); // should not panic
    }

    #[test]
    fn test_display_history_no_panic() {
        // Empty history
        display_history(&[]); // should not panic

        // History with entries
        let entries = vec![
            HistoryEntry {
                timestamp: "2025-01-01 12:00:00".into(),
                command: "status".into(),
                input_tokens: 500,
                output_tokens: 100,
                saved_tokens: 400,
                savings_pct: 80.0,
                duration_ms: 15,
            },
            HistoryEntry {
                timestamp: "2025-01-01 12:01:00".into(),
                command: "diff".into(),
                input_tokens: 2000,
                output_tokens: 400,
                saved_tokens: 1600,
                savings_pct: 80.0,
                duration_ms: 42,
            },
        ];
        display_history(&entries); // should not panic
    }
}