claudectl 0.26.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
#![allow(dead_code)]

use crate::config::HealthThresholds;
use crate::session::ClaudeSession;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Severity {
    Info,
    Warning,
    Critical,
}

#[derive(Debug, Clone)]
pub struct HealthCheck {
    pub icon: &'static str,
    pub name: &'static str,
    pub severity: Severity,
    pub message: String,
}

/// Run all health checks against a session. Returns warnings sorted by severity.
pub fn check_session(session: &ClaudeSession, t: &HealthThresholds) -> Vec<HealthCheck> {
    let mut checks = Vec::new();

    if let Some(c) = check_cache_health(session, t) {
        checks.push(c);
    }
    if let Some(c) = check_cost_spike(session, t) {
        checks.push(c);
    }
    if let Some(c) = check_loop_detection(session, t) {
        checks.push(c);
    }
    if let Some(c) = check_stalled(session, t) {
        checks.push(c);
    }
    if let Some(c) = check_context_saturation(session, t) {
        checks.push(c);
    }

    // Sort: Critical first, then Warning, then Info
    checks.sort_by_key(|c| match c.severity {
        Severity::Critical => 0,
        Severity::Warning => 1,
        Severity::Info => 2,
    });

    checks
}

/// Return the most severe health icon for display in the table, or empty string if healthy.
pub fn status_icon(session: &ClaudeSession, t: &HealthThresholds) -> &'static str {
    let checks = check_session(session, t);
    match checks.first() {
        Some(c) if c.severity == Severity::Critical => c.icon,
        Some(c) if c.severity == Severity::Warning => c.icon,
        _ => "",
    }
}

/// Format a compact health summary for the status bar.
pub fn format_health_summary(sessions: &[ClaudeSession], t: &HealthThresholds) -> Option<String> {
    let mut warnings = 0;
    let mut criticals = 0;
    let mut worst_msg = String::new();

    for session in sessions {
        for check in check_session(session, t) {
            match check.severity {
                Severity::Critical => {
                    criticals += 1;
                    if worst_msg.is_empty() {
                        worst_msg =
                            format!("{} {}: {}", check.icon, session.display_name(), check.name);
                    }
                }
                Severity::Warning => warnings += 1,
                Severity::Info => {}
            }
        }
    }

    if criticals == 0 && warnings == 0 {
        return None;
    }

    let count = criticals + warnings;
    Some(format!(
        "{} health issue{} | {}",
        count,
        if count == 1 { "" } else { "s" },
        worst_msg,
    ))
}

// ────────────────────────────────────────────────────────────────────────────
// Individual health checks
// ────────────────────────────────────────────────────────────────────────────

/// Detect low cache hit ratio (e.g., cache TTL bug causing 12x cost).
fn check_cache_health(session: &ClaudeSession, t: &HealthThresholds) -> Option<HealthCheck> {
    let total_input = session.total_input_tokens;
    let cache_read = session.cache_read_tokens;

    if total_input < t.cache_min_tokens {
        return None;
    }

    let hit_ratio = cache_read as f64 / total_input as f64;
    let critical_threshold = t.cache_critical_pct / 100.0;
    let warning_threshold = t.cache_warning_pct / 100.0;

    if hit_ratio < critical_threshold {
        Some(HealthCheck {
            icon: "🔥",
            name: "low cache",
            severity: Severity::Critical,
            message: format!(
                "Cache hit ratio is {:.0}% — expected >50% for long sessions. \
                 Possible cache TTL issue (check telemetry settings).",
                hit_ratio * 100.0
            ),
        })
    } else if hit_ratio < warning_threshold {
        Some(HealthCheck {
            icon: "",
            name: "low cache",
            severity: Severity::Warning,
            message: format!(
                "Cache hit ratio is {:.0}% — below typical range. \
                 May indicate cache TTL or model configuration issue.",
                hit_ratio * 100.0
            ),
        })
    } else {
        None
    }
}

/// Detect burn rate spikes — paying more for less output.
fn check_cost_spike(session: &ClaudeSession, t: &HealthThresholds) -> Option<HealthCheck> {
    if session.cost_usd < 1.0 || session.burn_rate_per_hr <= 0.0 {
        return None;
    }

    let elapsed_hrs = session.elapsed.as_secs_f64() / 3600.0;
    if elapsed_hrs < 0.01 {
        return None;
    }
    let avg_rate = session.cost_usd / elapsed_hrs;

    if avg_rate <= 0.0 {
        return None;
    }

    let spike_factor = session.burn_rate_per_hr / avg_rate;

    if spike_factor > t.cost_spike_critical {
        Some(HealthCheck {
            icon: "💸",
            name: "cost spike",
            severity: Severity::Critical,
            message: format!(
                "Burn rate ${:.1}/hr is {:.0}x the session average ${:.1}/hr.",
                session.burn_rate_per_hr, spike_factor, avg_rate,
            ),
        })
    } else if spike_factor > t.cost_spike_warning {
        Some(HealthCheck {
            icon: "💰",
            name: "cost spike",
            severity: Severity::Warning,
            message: format!(
                "Burn rate ${:.1}/hr is {:.1}x the session average.",
                session.burn_rate_per_hr, spike_factor,
            ),
        })
    } else {
        None
    }
}

/// Detect tool error loops — same tool failing repeatedly.
fn check_loop_detection(session: &ClaudeSession, t: &HealthThresholds) -> Option<HealthCheck> {
    if !session.last_tool_error {
        return None;
    }

    let max_calls = session
        .tool_usage
        .values()
        .map(|ts| ts.calls)
        .max()
        .unwrap_or(0);

    if max_calls >= t.loop_max_calls && session.last_tool_error {
        let tool_name = session
            .tool_usage
            .iter()
            .max_by_key(|(_, ts)| ts.calls)
            .map(|(name, _)| name.as_str())
            .unwrap_or("?");

        Some(HealthCheck {
            icon: "🔄",
            name: "looping",
            severity: Severity::Warning,
            message: format!(
                "{tool_name} called {max_calls} times with recent errors — may be stuck in a retry loop.",
            ),
        })
    } else {
        None
    }
}

/// Detect stalled sessions — high cost but no file output.
fn check_stalled(session: &ClaudeSession, t: &HealthThresholds) -> Option<HealthCheck> {
    if session.cost_usd < t.stall_min_cost {
        return None;
    }

    let files_edited: u32 = session.files_modified.values().sum();
    let elapsed_mins = session.elapsed.as_secs() / 60;

    if files_edited == 0 && elapsed_mins > t.stall_min_minutes {
        Some(HealthCheck {
            icon: "🐌",
            name: "stalled",
            severity: Severity::Warning,
            message: format!(
                "Spent ${:.1} over {} min with no file edits.",
                session.cost_usd, elapsed_mins,
            ),
        })
    } else {
        None
    }
}

/// Detect context window saturation.
fn check_context_saturation(session: &ClaudeSession, t: &HealthThresholds) -> Option<HealthCheck> {
    if session.context_max == 0 {
        return None;
    }

    let pct = (session.context_tokens as f64 / session.context_max as f64) * 100.0;

    if pct > t.context_critical_pct {
        Some(HealthCheck {
            icon: "🧠",
            name: "context full",
            severity: Severity::Critical,
            message: format!(
                "Context at {:.0}% — session may degrade or auto-compact. \
                 Consider spawning a fresh session.",
                pct,
            ),
        })
    } else if pct > t.context_warning_pct {
        Some(HealthCheck {
            icon: "🧠",
            name: "context high",
            severity: Severity::Warning,
            message: format!("Context at {:.0}% — approaching limit.", pct),
        })
    } else {
        None
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::session::{RawSession, SessionStatus, TelemetryStatus};

    fn defaults() -> HealthThresholds {
        HealthThresholds::default()
    }

    fn make_session() -> ClaudeSession {
        let raw = RawSession {
            pid: 1,
            session_id: "test".into(),
            cwd: "/tmp/test".into(),
            started_at: 0,
        };
        let mut s = ClaudeSession::from_raw(raw);
        s.status = SessionStatus::Processing;
        s.telemetry_status = TelemetryStatus::Available;
        s.model = "opus".into();
        s
    }

    #[test]
    fn healthy_session_no_warnings() {
        let s = make_session();
        assert!(check_session(&s, &defaults()).is_empty());
    }

    #[test]
    fn low_cache_critical() {
        let mut s = make_session();
        s.total_input_tokens = 100_000;
        s.cache_read_tokens = 5_000; // 5% hit ratio
        let checks = check_session(&s, &defaults());
        assert!(
            checks
                .iter()
                .any(|c| c.name == "low cache" && c.severity == Severity::Critical)
        );
    }

    #[test]
    fn low_cache_warning() {
        let mut s = make_session();
        s.total_input_tokens = 100_000;
        s.cache_read_tokens = 20_000; // 20% hit ratio
        let checks = check_session(&s, &defaults());
        assert!(
            checks
                .iter()
                .any(|c| c.name == "low cache" && c.severity == Severity::Warning)
        );
    }

    #[test]
    fn healthy_cache_no_warning() {
        let mut s = make_session();
        s.total_input_tokens = 100_000;
        s.cache_read_tokens = 60_000; // 60% hit ratio
        assert!(check_cache_health(&s, &defaults()).is_none());
    }

    #[test]
    fn context_saturation_critical() {
        let mut s = make_session();
        s.context_tokens = 190_000;
        s.context_max = 200_000;
        let checks = check_session(&s, &defaults());
        assert!(
            checks
                .iter()
                .any(|c| c.name == "context full" && c.severity == Severity::Critical)
        );
    }

    #[test]
    fn context_saturation_warning() {
        let mut s = make_session();
        s.context_tokens = 170_000;
        s.context_max = 200_000;
        let checks = check_session(&s, &defaults());
        assert!(
            checks
                .iter()
                .any(|c| c.name == "context high" && c.severity == Severity::Warning)
        );
    }

    #[test]
    fn stalled_detection() {
        let mut s = make_session();
        s.cost_usd = 10.0;
        s.elapsed = std::time::Duration::from_secs(15 * 60);
        // No files modified
        let checks = check_session(&s, &defaults());
        assert!(checks.iter().any(|c| c.name == "stalled"));
    }

    #[test]
    fn status_icon_returns_worst() {
        let mut s = make_session();
        s.context_tokens = 190_000;
        s.context_max = 200_000;
        assert_eq!(status_icon(&s, &defaults()), "🧠");
    }

    #[test]
    fn status_icon_empty_when_healthy() {
        let s = make_session();
        assert_eq!(status_icon(&s, &defaults()), "");
    }

    #[test]
    fn sorted_by_severity() {
        let mut s = make_session();
        s.total_input_tokens = 100_000;
        s.cache_read_tokens = 5_000; // Critical cache
        s.context_tokens = 170_000;
        s.context_max = 200_000; // Warning context
        let checks = check_session(&s, &defaults());
        assert!(checks.len() >= 2);
        assert_eq!(checks[0].severity, Severity::Critical);
    }

    #[test]
    fn custom_thresholds_change_trigger() {
        let mut s = make_session();
        s.total_input_tokens = 100_000;
        s.cache_read_tokens = 8_000; // 8% hit ratio — critical at default 10%

        // With defaults, this is critical
        let checks = check_session(&s, &defaults());
        assert!(
            checks
                .iter()
                .any(|c| c.name == "low cache" && c.severity == Severity::Critical)
        );

        // With relaxed threshold, this should only be a warning
        let mut relaxed = defaults();
        relaxed.cache_critical_pct = 5.0;
        let checks = check_session(&s, &relaxed);
        assert!(
            checks
                .iter()
                .any(|c| c.name == "low cache" && c.severity == Severity::Warning)
        );
        assert!(
            !checks
                .iter()
                .any(|c| c.name == "low cache" && c.severity == Severity::Critical)
        );
    }

    #[test]
    fn custom_context_thresholds() {
        let mut s = make_session();
        s.context_tokens = 170_000;
        s.context_max = 200_000; // 85% — warning at default 80%

        // With defaults, this triggers warning
        let checks = check_session(&s, &defaults());
        assert!(
            checks
                .iter()
                .any(|c| c.name == "context high" && c.severity == Severity::Warning)
        );

        // With tighter threshold (84%), 85% usage should trigger critical
        let mut tight = defaults();
        tight.context_critical_pct = 84.0;
        let checks = check_session(&s, &tight);
        assert!(
            checks
                .iter()
                .any(|c| c.name == "context full" && c.severity == Severity::Critical)
        );
    }
}