lowfat-core 0.1.0

Core types, config, tokens, SQLite tracking for lowfat
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
use crate::level::Level;
use crate::tokens::estimate_tokens;

/// A resolved pipeline set: normal chain + optional conditional chains.
#[derive(Debug, Clone)]
pub struct Pipeline {
    pub stages: Vec<PipelineStage>,
}

/// Conditional pipelines: different chains based on exit code or output patterns.
#[derive(Debug, Clone, Default)]
pub struct ConditionalPipelines {
    /// Default pipeline (always present).
    pub default: Option<Pipeline>,
    /// Pipeline when command exits non-zero.
    pub on_error: Option<Pipeline>,
    /// Pipeline when output is empty.
    pub on_empty: Option<Pipeline>,
    /// Pipeline when output exceeds token budget.
    pub on_large: Option<Pipeline>,
}

impl ConditionalPipelines {
    /// Select the right pipeline based on command result.
    pub fn select(&self, exit_code: i32, output: &str) -> Option<&Pipeline> {
        if exit_code != 0 {
            if let Some(ref p) = self.on_error {
                return Some(p);
            }
        }
        if output.is_empty() {
            if let Some(ref p) = self.on_empty {
                return Some(p);
            }
        }
        // "large" = > 1000 tokens
        if estimate_tokens(output) > 1000 {
            if let Some(ref p) = self.on_large {
                return Some(p);
            }
        }
        self.default.as_ref()
    }

    /// Whether any pipelines are configured.
    pub fn is_empty(&self) -> bool {
        self.default.is_none()
            && self.on_error.is_none()
            && self.on_empty.is_none()
            && self.on_large.is_none()
    }
}

/// A single stage in the pipeline.
/// Supports optional parameter via `name:param` syntax (e.g., `truncate:100`).
#[derive(Debug, Clone)]
pub struct PipelineStage {
    pub name: String,
    pub stage_type: StageType,
    /// Optional numeric parameter (e.g., line limit, token budget).
    pub param: Option<usize>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum StageType {
    /// Built-in processor (runs in-process, no plugin needed)
    Builtin,
    /// External plugin filter
    Plugin,
}

impl Pipeline {
    /// Create a pipeline with just one filter (backwards-compatible default).
    pub fn single(filter_name: &str) -> Self {
        Pipeline {
            stages: vec![PipelineStage {
                name: filter_name.to_string(),
                stage_type: StageType::Plugin,
                param: None,
            }],
        }
    }

    /// Build a pipeline from pre-processors, main filter, and post-processors.
    pub fn from_parts(pre: &[String], filter_name: &str, post: &[String]) -> Self {
        let mut stages = Vec::new();
        for name in pre {
            let (base, param) = parse_stage_spec(name);
            stages.push(PipelineStage {
                name: base,
                stage_type: resolve_stage_type(&name.split(':').next().unwrap_or(name)),
                param,
            });
        }
        stages.push(PipelineStage {
            name: filter_name.to_string(),
            stage_type: StageType::Plugin,
            param: None,
        });
        for name in post {
            let (base, param) = parse_stage_spec(name);
            stages.push(PipelineStage {
                name: base,
                stage_type: resolve_stage_type(&name.split(':').next().unwrap_or(name)),
                param,
            });
        }
        Pipeline { stages }
    }

    /// Parse a pipeline from a comma-separated string.
    /// Supports parameterized stages via `name:param` syntax.
    /// e.g., "strip-ansi, git-compact, truncate:100, token-budget:1500"
    pub fn parse(spec: &str) -> Self {
        let stages = spec
            .split(',')
            .map(|s| s.trim())
            .filter(|s| !s.is_empty())
            .map(|raw| {
                let (name, param) = parse_stage_spec(raw);
                let base_name = raw.split(':').next().unwrap_or(raw);
                PipelineStage {
                    name,
                    stage_type: resolve_stage_type(base_name),
                    param,
                }
            })
            .collect();
        Pipeline { stages }
    }

    pub fn len(&self) -> usize {
        self.stages.len()
    }

    pub fn is_empty(&self) -> bool {
        self.stages.is_empty()
    }

    /// Format as display string. Shows params when present (e.g., "truncate:100").
    pub fn display(&self) -> String {
        self.stages
            .iter()
            .map(|s| match s.param {
                Some(p) => format!("{}:{}", s.name, p),
                None => s.name.clone(),
            })
            .collect::<Vec<_>>()
            .join("")
    }
}

/// Parse conditional pipelines from .lowfat config lines.
/// Supports:
///   pipeline.git = strip-ansi,git-compact,truncate
///   pipeline.git.error = strip-ansi,head
///   pipeline.git.empty = passthrough
///   pipeline.git.large = strip-ansi,git-compact,token-budget
pub fn parse_conditional_pipeline(
    lines: &[(String, String)],
) -> ConditionalPipelines {
    let mut cp = ConditionalPipelines::default();
    for (key, spec) in lines {
        match key.as_str() {
            "" => cp.default = Some(Pipeline::parse(spec)),
            "error" => cp.on_error = Some(Pipeline::parse(spec)),
            "empty" => cp.on_empty = Some(Pipeline::parse(spec)),
            "large" => cp.on_large = Some(Pipeline::parse(spec)),
            _ => {} // unknown condition, ignore
        }
    }
    cp
}

/// Parse "name:param" into (name, Option<param>).
/// e.g., "truncate:100" → ("truncate", Some(100)), "strip-ansi" → ("strip-ansi", None)
fn parse_stage_spec(spec: &str) -> (String, Option<usize>) {
    match spec.split_once(':') {
        Some((name, param)) => {
            let param = param.trim().parse::<usize>().ok();
            (name.trim().to_string(), param)
        }
        None => (spec.to_string(), None),
    }
}

/// Determine if a stage name is a built-in processor or an external plugin.
fn resolve_stage_type(name: &str) -> StageType {
    match name {
        "strip-ansi" | "truncate" | "token-budget" | "dedup-blank" | "head" | "passthrough" => {
            StageType::Builtin
        }
        _ => StageType::Plugin,
    }
}

// --- Built-in processors ---

/// Strip ANSI escape codes.
pub fn proc_strip_ansi(text: &str) -> String {
    let mut result = String::with_capacity(text.len());
    let mut chars = text.chars().peekable();
    while let Some(ch) = chars.next() {
        if ch == '\x1b' {
            if chars.peek() == Some(&'[') {
                chars.next();
                while let Some(&c) = chars.peek() {
                    chars.next();
                    if c.is_ascii_alphabetic() {
                        break;
                    }
                }
                continue;
            }
        }
        result.push(ch);
    }
    result
}

/// Truncate text to N lines.
pub fn proc_truncate(text: &str, max_lines: usize) -> String {
    let lines: Vec<&str> = text.lines().collect();
    if lines.len() <= max_lines {
        return text.to_string();
    }
    let mut result: String = lines[..max_lines].join("\n");
    result.push_str(&format!(
        "\n... ({} lines truncated)",
        lines.len() - max_lines
    ));
    result
}

/// Enforce a token budget.
pub fn proc_token_budget(text: &str, max_tokens: usize) -> String {
    let current = estimate_tokens(text);
    if current <= max_tokens {
        return text.to_string();
    }
    let ratio = max_tokens as f64 / current as f64;
    let target_chars = (text.len() as f64 * ratio) as usize;
    let mut result = text[..target_chars.min(text.len())].to_string();
    if let Some(pos) = result.rfind('\n') {
        result.truncate(pos);
    }
    let truncated_tokens = estimate_tokens(&result);
    result.push_str(&format!(
        "\n... (truncated to ~{} tokens from {})",
        truncated_tokens, current
    ));
    result
}

/// Remove consecutive blank lines (keep max 1).
pub fn proc_dedup_blank(text: &str) -> String {
    let mut result = String::with_capacity(text.len());
    let mut prev_blank = false;
    for line in text.lines() {
        if line.trim().is_empty() {
            if !prev_blank {
                result.push('\n');
                prev_blank = true;
            }
        } else {
            result.push_str(line);
            result.push('\n');
            prev_blank = false;
        }
    }
    result
}

/// Apply a built-in processor by name. Returns None if not a built-in.
/// When `param` is Some, it overrides the level-based default.
pub fn apply_builtin(name: &str, text: &str, level: Level, param: Option<usize>) -> Option<String> {
    match name {
        "strip-ansi" => Some(proc_strip_ansi(text)),
        "truncate" => {
            let limit = param.unwrap_or_else(|| level.head_limit(200));
            Some(proc_truncate(text, limit))
        }
        "head" => {
            let limit = param.unwrap_or_else(|| level.head_limit(40));
            Some(proc_truncate(text, limit))
        }
        "token-budget" => {
            let budget = param.unwrap_or_else(|| match level {
                Level::Lite => 2000,
                Level::Full => 1000,
                Level::Ultra => 500,
            });
            Some(proc_token_budget(text, budget))
        }
        "dedup-blank" => Some(proc_dedup_blank(text)),
        "passthrough" => Some(text.to_string()),
        _ => None,
    }
}

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

    #[test]
    fn pipeline_single() {
        let p = Pipeline::single("git-compact");
        assert_eq!(p.len(), 1);
        assert_eq!(p.stages[0].name, "git-compact");
        assert_eq!(p.display(), "git-compact");
    }

    #[test]
    fn pipeline_from_parts() {
        let p = Pipeline::from_parts(
            &["strip-ansi".to_string()],
            "git-compact",
            &["truncate".to_string()],
        );
        assert_eq!(p.len(), 3);
        assert_eq!(p.stages[0].stage_type, StageType::Builtin);
        assert_eq!(p.stages[1].stage_type, StageType::Plugin);
        assert_eq!(p.stages[2].stage_type, StageType::Builtin);
        assert_eq!(p.display(), "strip-ansi → git-compact → truncate");
    }

    #[test]
    fn pipeline_parse() {
        let p = Pipeline::parse("strip-ansi, git-compact, truncate");
        assert_eq!(p.len(), 3);
        assert_eq!(p.stages[0].name, "strip-ansi");
        assert_eq!(p.stages[1].name, "git-compact");
        assert_eq!(p.stages[2].name, "truncate");
    }

    #[test]
    fn conditional_select_default() {
        let cp = ConditionalPipelines {
            default: Some(Pipeline::single("git-compact")),
            ..Default::default()
        };
        let p = cp.select(0, "some output").unwrap();
        assert_eq!(p.stages[0].name, "git-compact");
    }

    #[test]
    fn conditional_select_error() {
        let cp = ConditionalPipelines {
            default: Some(Pipeline::single("git-compact")),
            on_error: Some(Pipeline::parse("strip-ansi,head")),
            ..Default::default()
        };
        // exit_code != 0 → on_error
        let p = cp.select(1, "error output").unwrap();
        assert_eq!(p.display(), "strip-ansi → head");
        // exit_code == 0 → default
        let p = cp.select(0, "ok output").unwrap();
        assert_eq!(p.display(), "git-compact");
    }

    #[test]
    fn conditional_select_large() {
        let cp = ConditionalPipelines {
            default: Some(Pipeline::single("git-compact")),
            on_large: Some(Pipeline::parse("git-compact,token-budget")),
            ..Default::default()
        };
        let large_output = "x".repeat(5000); // > 1000 tokens
        let p = cp.select(0, &large_output).unwrap();
        assert_eq!(p.display(), "git-compact → token-budget");
    }

    #[test]
    fn conditional_select_empty() {
        let cp = ConditionalPipelines {
            default: Some(Pipeline::single("git-compact")),
            on_empty: Some(Pipeline::parse("passthrough")),
            ..Default::default()
        };
        let p = cp.select(0, "").unwrap();
        assert_eq!(p.display(), "passthrough");
    }

    #[test]
    fn conditional_parse() {
        let lines = vec![
            ("".to_string(), "strip-ansi,git-compact".to_string()),
            ("error".to_string(), "head".to_string()),
            ("large".to_string(), "git-compact,token-budget".to_string()),
        ];
        let cp = parse_conditional_pipeline(&lines);
        assert!(cp.default.is_some());
        assert!(cp.on_error.is_some());
        assert!(cp.on_large.is_some());
        assert!(cp.on_empty.is_none());
    }

    #[test]
    fn strip_ansi_basic() {
        let input = "\x1b[31mERROR\x1b[0m: something failed";
        assert_eq!(proc_strip_ansi(input), "ERROR: something failed");
    }

    #[test]
    fn strip_ansi_clean() {
        assert_eq!(proc_strip_ansi("no escape codes"), "no escape codes");
    }

    #[test]
    fn truncate_within_limit() {
        let input = "line1\nline2\nline3";
        assert_eq!(proc_truncate(input, 5), input);
    }

    #[test]
    fn truncate_over_limit() {
        let input = "line1\nline2\nline3\nline4\nline5";
        let result = proc_truncate(input, 3);
        assert!(result.starts_with("line1\nline2\nline3"));
        assert!(result.contains("2 lines truncated"));
    }

    #[test]
    fn token_budget_within() {
        assert_eq!(proc_token_budget("short", 100), "short");
    }

    #[test]
    fn token_budget_over() {
        let input = "a".repeat(400); // 100 tokens
        let result = proc_token_budget(&input, 50);
        assert!(result.len() < input.len());
        assert!(result.contains("truncated to"));
    }

    #[test]
    fn dedup_blank() {
        let input = "line1\n\n\n\nline2\n\nline3";
        assert_eq!(proc_dedup_blank(input), "line1\n\nline2\n\nline3\n");
    }

    #[test]
    fn apply_builtin_known() {
        assert!(apply_builtin("strip-ansi", "t", Level::Full, None).is_some());
        assert!(apply_builtin("truncate", "t", Level::Full, None).is_some());
        assert!(apply_builtin("token-budget", "t", Level::Full, None).is_some());
        assert!(apply_builtin("dedup-blank", "t", Level::Full, None).is_some());
        assert!(apply_builtin("head", "t", Level::Full, None).is_some());
        assert!(apply_builtin("passthrough", "t", Level::Full, None).is_some());
    }

    #[test]
    fn apply_builtin_unknown() {
        assert!(apply_builtin("git-compact", "t", Level::Full, None).is_none());
    }

    #[test]
    fn parse_parameterized_stages() {
        let p = Pipeline::parse("strip-ansi, truncate:100, token-budget:1500");
        assert_eq!(p.len(), 3);
        assert_eq!(p.stages[0].name, "strip-ansi");
        assert_eq!(p.stages[0].param, None);
        assert_eq!(p.stages[1].name, "truncate");
        assert_eq!(p.stages[1].param, Some(100));
        assert_eq!(p.stages[2].name, "token-budget");
        assert_eq!(p.stages[2].param, Some(1500));
    }

    #[test]
    fn display_with_params() {
        let p = Pipeline::parse("strip-ansi, git-compact, truncate:100");
        assert_eq!(p.display(), "strip-ansi → git-compact → truncate:100");
    }

    #[test]
    fn param_overrides_level_default() {
        let lines = (0..500).map(|i| format!("line{i}")).collect::<Vec<_>>().join("\n");
        // Without param: Full level truncate = 200 lines
        let default_result = apply_builtin("truncate", &lines, Level::Full, None).unwrap();
        assert!(default_result.contains("truncated"));
        // With param: override to 50 lines
        let custom_result = apply_builtin("truncate", &lines, Level::Full, Some(50)).unwrap();
        assert!(custom_result.contains("truncated"));
        assert!(custom_result.lines().count() < default_result.lines().count());
    }
}