claudectl 0.35.0

Auto-pilot for Claude Code — a local model watches every session and decides what to approve
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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
#![allow(dead_code)]

use std::collections::{HashMap, HashSet};
use std::fs;
use std::path::PathBuf;

use super::decisions::{DecisionRecord, DistilledPreferences};

// ────────────────────────────────────────────────────────────────────────────
// Data structures
// ────────────────────────────────────────────────────────────────────────────

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum InsightCategory {
    FrictionPattern,
    ErrorLoop,
    ContextBlowout,
    MissingRule,
    AccuracyGap,
    TemporalFriction,
    CostPattern,
}

impl InsightCategory {
    fn label(&self) -> &'static str {
        match self {
            InsightCategory::FrictionPattern => "friction_pattern",
            InsightCategory::ErrorLoop => "error_loop",
            InsightCategory::ContextBlowout => "context_blowout",
            InsightCategory::MissingRule => "missing_rule",
            InsightCategory::AccuracyGap => "accuracy_gap",
            InsightCategory::TemporalFriction => "temporal_friction",
            InsightCategory::CostPattern => "cost_pattern",
        }
    }

    fn from_label(s: &str) -> Option<Self> {
        match s {
            "friction_pattern" => Some(InsightCategory::FrictionPattern),
            "error_loop" => Some(InsightCategory::ErrorLoop),
            "context_blowout" => Some(InsightCategory::ContextBlowout),
            "missing_rule" => Some(InsightCategory::MissingRule),
            "accuracy_gap" => Some(InsightCategory::AccuracyGap),
            "temporal_friction" => Some(InsightCategory::TemporalFriction),
            "cost_pattern" => Some(InsightCategory::CostPattern),
            _ => None,
        }
    }

    fn display_name(&self) -> &'static str {
        match self {
            InsightCategory::FrictionPattern => "Friction Patterns",
            InsightCategory::ErrorLoop => "Error Loops",
            InsightCategory::ContextBlowout => "Context Blowouts",
            InsightCategory::MissingRule => "Recommended Rules",
            InsightCategory::AccuracyGap => "Accuracy Gaps",
            InsightCategory::TemporalFriction => "Temporal Patterns",
            InsightCategory::CostPattern => "Cost Patterns",
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum InsightSeverity {
    Info,
    Suggestion,
    Warning,
    Critical,
}

impl InsightSeverity {
    fn label(&self) -> &'static str {
        match self {
            InsightSeverity::Info => "info",
            InsightSeverity::Suggestion => "suggestion",
            InsightSeverity::Warning => "warning",
            InsightSeverity::Critical => "critical",
        }
    }

    fn from_label(s: &str) -> Self {
        match s {
            "critical" => InsightSeverity::Critical,
            "warning" => InsightSeverity::Warning,
            "suggestion" => InsightSeverity::Suggestion,
            _ => InsightSeverity::Info,
        }
    }
}

#[derive(Debug, Clone)]
pub struct Insight {
    pub fingerprint: String,
    pub generated_at: u64,
    pub category: InsightCategory,
    pub severity: InsightSeverity,
    pub summary: String,
    pub suggestion: Option<String>,
    pub evidence_count: u32,
}

pub struct InsightState {
    pub seen_fingerprints: HashSet<String>,
    pub last_generated: u64,
    pub current_insights: Vec<Insight>,
}

// ────────────────────────────────────────────────────────────────────────────
// Mode toggle (on/off)
// ────────────────────────────────────────────────────────────────────────────

fn insights_mode_path() -> PathBuf {
    super::decisions::decisions_dir().join("insights-mode")
}

/// Read the current insights mode. Returns "off" if no file exists (opt-in).
pub fn read_insights_mode() -> String {
    let path = insights_mode_path();
    fs::read_to_string(&path)
        .map(|s| s.trim().to_string())
        .unwrap_or_else(|_| "off".into())
}

/// Write the insights mode to disk.
pub fn write_insights_mode(mode: &str) -> Result<(), String> {
    let path = insights_mode_path();
    if let Some(parent) = path.parent() {
        let _ = fs::create_dir_all(parent);
    }
    if mode == "off" {
        let _ = fs::remove_file(&path);
        Ok(())
    } else {
        fs::write(&path, mode).map_err(|e| format!("write error: {e}"))
    }
}

// ────────────────────────────────────────────────────────────────────────────
// Persistence
// ────────────────────────────────────────────────────────────────────────────

fn insights_path() -> PathBuf {
    super::decisions::decisions_dir().join("insights.json")
}

pub(super) fn epoch_now() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs()
}

pub fn load_state() -> InsightState {
    let path = insights_path();
    let content = match fs::read_to_string(&path) {
        Ok(c) => c,
        Err(_) => {
            return InsightState {
                seen_fingerprints: HashSet::new(),
                last_generated: 0,
                current_insights: Vec::new(),
            };
        }
    };

    let json: serde_json::Value = match serde_json::from_str(&content) {
        Ok(v) => v,
        Err(_) => {
            return InsightState {
                seen_fingerprints: HashSet::new(),
                last_generated: 0,
                current_insights: Vec::new(),
            };
        }
    };

    let seen = json
        .get("seen_fingerprints")
        .and_then(|v| v.as_array())
        .map(|arr| {
            arr.iter()
                .filter_map(|v| v.as_str().map(|s| s.to_string()))
                .collect::<HashSet<_>>()
        })
        .unwrap_or_default();

    let last_generated = json
        .get("last_generated")
        .and_then(|v| v.as_u64())
        .unwrap_or(0);

    let current = json
        .get("current_insights")
        .and_then(|v| v.as_array())
        .map(|arr| arr.iter().filter_map(parse_insight_json).collect())
        .unwrap_or_default();

    InsightState {
        seen_fingerprints: seen,
        last_generated,
        current_insights: current,
    }
}

pub fn save_state(state: &InsightState) -> Result<(), String> {
    let path = insights_path();
    if let Some(parent) = path.parent() {
        let _ = fs::create_dir_all(parent);
    }

    let json = serde_json::json!({
        "seen_fingerprints": state.seen_fingerprints.iter().collect::<Vec<_>>(),
        "last_generated": state.last_generated,
        "current_insights": state.current_insights.iter().map(insight_to_json).collect::<Vec<_>>(),
    });

    fs::write(
        &path,
        serde_json::to_string_pretty(&json).map_err(|e| format!("json error: {e}"))?,
    )
    .map_err(|e| format!("write error: {e}"))
}

fn insight_to_json(i: &Insight) -> serde_json::Value {
    serde_json::json!({
        "fingerprint": i.fingerprint,
        "generated_at": i.generated_at,
        "category": i.category.label(),
        "severity": i.severity.label(),
        "summary": i.summary,
        "suggestion": i.suggestion,
        "evidence_count": i.evidence_count,
    })
}

fn parse_insight_json(v: &serde_json::Value) -> Option<Insight> {
    Some(Insight {
        fingerprint: v.get("fingerprint")?.as_str()?.to_string(),
        generated_at: v.get("generated_at")?.as_u64()?,
        category: InsightCategory::from_label(v.get("category")?.as_str()?)?,
        severity: InsightSeverity::from_label(
            v.get("severity").and_then(|s| s.as_str()).unwrap_or("info"),
        ),
        summary: v.get("summary")?.as_str()?.to_string(),
        suggestion: v
            .get("suggestion")
            .and_then(|s| s.as_str())
            .map(|s| s.to_string()),
        evidence_count: v.get("evidence_count")?.as_u64()? as u32,
    })
}

// ────────────────────────────────────────────────────────────────────────────
// Differential merging
// ────────────────────────────────────────────────────────────────────────────

/// Merge newly generated insights with existing state.
/// Returns only the insights that are NEW (unseen fingerprints).
/// Updates `state.seen_fingerprints` and `state.current_insights`.
pub fn merge_insights(generated: Vec<Insight>, state: &mut InsightState) -> Vec<Insight> {
    // Prune seen fingerprints that are no longer in the current set
    let current_fps: HashSet<String> = generated.iter().map(|i| i.fingerprint.clone()).collect();
    state
        .seen_fingerprints
        .retain(|fp| current_fps.contains(fp));

    // Filter to only unseen
    let new: Vec<Insight> = generated
        .iter()
        .filter(|i| !state.seen_fingerprints.contains(&i.fingerprint))
        .cloned()
        .collect();

    // Mark new as seen
    for i in &new {
        state.seen_fingerprints.insert(i.fingerprint.clone());
    }

    state.current_insights = generated;
    state.last_generated = epoch_now();
    new
}

// Import detectors for use by generate_insights()
use super::detectors::{
    detect_accuracy_gaps, detect_context_blowouts, detect_cost_patterns, detect_error_loops,
    detect_friction_patterns, detect_missing_rules, detect_temporal_friction,
};

// ────────────────────────────────────────────────────────────────────────────
// Main generation entry point
// ────────────────────────────────────────────────────────────────────────────

/// Generate all insights from the decision history and distilled preferences.
/// Runs all detectors, sorts results by severity (critical first).
pub fn generate_insights(
    decisions: &[DecisionRecord],
    prefs: &DistilledPreferences,
) -> Vec<Insight> {
    let mut insights = Vec::new();
    insights.extend(detect_friction_patterns(decisions));
    insights.extend(detect_error_loops(decisions));
    insights.extend(detect_context_blowouts(decisions));
    insights.extend(detect_missing_rules(decisions, prefs));
    insights.extend(detect_accuracy_gaps(prefs));
    insights.extend(detect_temporal_friction(prefs));
    insights.extend(detect_cost_patterns(decisions));

    // Sort by severity descending, then by evidence count descending
    insights.sort_by(|a, b| {
        b.severity
            .cmp(&a.severity)
            .then_with(|| b.evidence_count.cmp(&a.evidence_count))
    });

    insights
}

// ────────────────────────────────────────────────────────────────────────────
// Formatting
// ────────────────────────────────────────────────────────────────────────────

/// Format a list of insights grouped by category.
fn format_insights(insights: &[Insight], header: &str) -> String {
    if insights.is_empty() {
        return String::new();
    }

    let mut lines = Vec::new();
    lines.push(header.to_string());
    lines.push("\u{2500}".repeat(header.len()));
    lines.push(String::new());

    // Group by category (preserving order of first appearance)
    let mut categories: Vec<InsightCategory> = Vec::new();
    let mut by_category: HashMap<InsightCategory, Vec<&Insight>> = HashMap::new();

    // Determine category order from enum variants for consistent display
    let category_order = [
        InsightCategory::FrictionPattern,
        InsightCategory::ErrorLoop,
        InsightCategory::ContextBlowout,
        InsightCategory::MissingRule,
        InsightCategory::AccuracyGap,
        InsightCategory::TemporalFriction,
        InsightCategory::CostPattern,
    ];

    for i in insights {
        by_category.entry(i.category).or_default().push(i);
    }

    for cat in &category_order {
        if let Some(group) = by_category.get(cat) {
            if !categories.contains(cat) {
                categories.push(*cat);
            }
            lines.push(format!("  {}", cat.display_name()));
            for insight in group {
                lines.push(format!("  - {}", insight.summary));
                if let Some(ref suggestion) = insight.suggestion {
                    lines.push(format!("    \u{2192} {suggestion}"));
                }
            }
            lines.push(String::new());
        }
    }

    lines.join("\n")
}

// ────────────────────────────────────────────────────────────────────────────
// CLI handler
// ────────────────────────────────────────────────────────────────────────────

/// Print insights to stdout. Called from main.rs --insights handler.
pub fn print_insights() {
    let decisions = super::decisions::read_all_decisions();
    if decisions.is_empty() {
        println!("No decision history yet. Use claudectl with --brain to build history.");
        return;
    }

    let prefs = super::decisions::load_preferences()
        .unwrap_or_else(|| super::decisions::distill_preferences(&decisions));

    let insights = generate_insights(&decisions, &prefs);
    let mut state = load_state();
    let new_insights = merge_insights(insights, &mut state);
    let _ = save_state(&state);

    if state.current_insights.is_empty() {
        println!("No insights detected. Keep using claudectl to build more history.");
        return;
    }

    let mode = read_insights_mode();
    println!(
        "Insights mode: {mode}{}",
        if mode == "off" {
            " (run claudectl --brain --insights on to enable auto-generation)"
        } else {
            ""
        }
    );
    println!();

    if !new_insights.is_empty() {
        print!(
            "{}",
            format_insights(
                &new_insights,
                &format!("New Insights ({} new)", new_insights.len()),
            )
        );
    }

    print!(
        "{}",
        format_insights(
            &state.current_insights,
            &format!("All Insights ({} total)", state.current_insights.len()),
        )
    );
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::brain::decisions::{
        DecisionContext, DecisionType, DistilledPreferences, PreferencePattern, ToolAccuracy,
    };

    fn make_decision(tool: &str, command: &str, user_action: &str, pid: u32) -> DecisionRecord {
        DecisionRecord {
            timestamp: "0".to_string(),
            pid,
            project: "test".to_string(),
            tool: Some(tool.to_string()),
            command: Some(command.to_string()),
            brain_action: "approve".to_string(),
            brain_confidence: 0.8,
            brain_reasoning: String::new(),
            user_action: user_action.to_string(),
            context: None,
            outcome: None,
            decision_type: DecisionType::Session,
            suggested_at: None,
        }
    }

    #[allow(clippy::too_many_arguments)]
    fn make_decision_with_context(
        tool: &str,
        command: &str,
        user_action: &str,
        pid: u32,
        context_pct: u8,
        last_error: bool,
        burn_rate: f64,
        cost: f64,
    ) -> DecisionRecord {
        let mut d = make_decision(tool, command, user_action, pid);
        d.context = Some(DecisionContext {
            cost_usd: cost,
            context_pct,
            last_tool_error: last_error,
            error_message: None,
            model: "test".to_string(),
            elapsed_secs: 100,
            files_modified_count: 0,
            total_tool_calls: 10,
            has_file_conflict: false,
            status: "Processing".to_string(),
            burn_rate_per_hr: burn_rate,
            recent_error_count: 0,
            subagent_count: 0,
            hour: Some(10),
        });
        d
    }

    fn empty_prefs() -> DistilledPreferences {
        DistilledPreferences {
            patterns: Vec::new(),
            tool_accuracy: Vec::new(),
            total_decisions: 0,
            overall_accuracy: 0.0,
            temporal: Vec::new(),
        }
    }

    #[test]
    fn test_differential_merging() {
        let insights = vec![
            Insight {
                fingerprint: "friction:Bash:npm install".to_string(),
                generated_at: 100,
                category: InsightCategory::FrictionPattern,
                severity: InsightSeverity::Warning,
                summary: "test".to_string(),
                suggestion: None,
                evidence_count: 5,
            },
            Insight {
                fingerprint: "accuracy_gap:Edit".to_string(),
                generated_at: 100,
                category: InsightCategory::AccuracyGap,
                severity: InsightSeverity::Suggestion,
                summary: "test2".to_string(),
                suggestion: None,
                evidence_count: 3,
            },
        ];

        let mut state = InsightState {
            seen_fingerprints: HashSet::new(),
            last_generated: 0,
            current_insights: Vec::new(),
        };

        // First merge: both are new
        let new = merge_insights(insights.clone(), &mut state);
        assert_eq!(new.len(), 2);
        assert_eq!(state.seen_fingerprints.len(), 2);

        // Second merge: none are new (already seen)
        let new2 = merge_insights(insights.clone(), &mut state);
        assert_eq!(new2.len(), 0);
        assert_eq!(state.current_insights.len(), 2);
    }

    #[test]
    fn test_stale_fingerprints_pruned() {
        let mut state = InsightState {
            seen_fingerprints: {
                let mut s = HashSet::new();
                s.insert("old_fingerprint".to_string());
                s.insert("accuracy_gap:Edit".to_string());
                s
            },
            last_generated: 0,
            current_insights: Vec::new(),
        };

        // Only one insight — the old_fingerprint should be pruned
        let insights = vec![Insight {
            fingerprint: "accuracy_gap:Edit".to_string(),
            generated_at: 100,
            category: InsightCategory::AccuracyGap,
            severity: InsightSeverity::Suggestion,
            summary: "test".to_string(),
            suggestion: None,
            evidence_count: 3,
        }];

        let _new = merge_insights(insights, &mut state);
        assert!(!state.seen_fingerprints.contains("old_fingerprint"));
        assert!(state.seen_fingerprints.contains("accuracy_gap:Edit"));
    }

    #[test]
    fn test_generate_insights_sorts_by_severity() {
        let prefs = DistilledPreferences {
            patterns: vec![PreferencePattern {
                tool: "Bash".to_string(),
                command_pattern: Some("cargo test".to_string()),
                preferred_action: "approve".to_string(),
                sample_count: 15,
                accept_rate: 1.0,
                conditions: Vec::new(),
                confidence: 1.0,
            }],
            tool_accuracy: vec![ToolAccuracy {
                tool: "Edit".to_string(),
                total: 10,
                correct: 3,
                confidence_threshold: 0.9,
            }],
            total_decisions: 25,
            overall_accuracy: 0.5,
            temporal: Vec::new(),
        };

        let mut decisions = Vec::new();
        // Add friction pattern (Warning severity)
        for i in 0..10 {
            decisions.push(make_decision("Bash", "npm install", "reject", i));
        }

        let insights = generate_insights(&decisions, &prefs);
        assert!(!insights.is_empty());

        // Verify sorted: warnings before suggestions
        for window in insights.windows(2) {
            assert!(window[0].severity >= window[1].severity);
        }
    }

    #[test]
    fn test_empty_decisions_no_insights() {
        let insights = generate_insights(&[], &empty_prefs());
        assert!(insights.is_empty());
    }

    #[test]
    fn test_format_insights_output() {
        let insights = vec![Insight {
            fingerprint: "friction:Bash:npm install".to_string(),
            generated_at: 100,
            category: InsightCategory::FrictionPattern,
            severity: InsightSeverity::Warning,
            summary: "[Bash] \"npm install\" rejected 8/10 times".to_string(),
            suggestion: Some("consider adding deny rule".to_string()),
            evidence_count: 10,
        }];

        let output = format_insights(&insights, "Test Header");
        assert!(output.contains("Friction Patterns"));
        assert!(output.contains("npm install"));
        assert!(output.contains("consider adding deny rule"));
    }
}