lowfat 0.4.0

CLI binary for lowfat
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
use anyhow::Result;
use lowfat_core::config::RunfConfig;
use lowfat_core::lf::{self, Op};
use lowfat_plugin::discovery::discover_plugins;
use std::io::Write;
use std::process::{Command, Stdio};

pub fn list() -> Result<()> {
    let config = RunfConfig::resolve();
    let plugins = discover_plugins(&config.plugin_dir);

    if plugins.is_empty() {
        println!("No community plugins installed.");
        println!("  Plugin dir: {}", config.plugin_dir.display());
        return Ok(());
    }

    println!("Community plugins:");
    println!();
    for plugin in &plugins {
        let m = &plugin.manifest;
        let name = &m.plugin.name;
        let version = m.plugin.version.as_deref().unwrap_or("?");
        let cmds = m.plugin.commands.join(", ");
        let category = &plugin.category;

        println!(
            "  {category}/{name} v{version} — commands: [{cmds}]"
        );
    }

    Ok(())
}

pub fn doctor() -> Result<()> {
    let config = RunfConfig::resolve();
    let plugins = discover_plugins(&config.plugin_dir);

    if plugins.is_empty() {
        println!("No community plugins to check.");
        return Ok(());
    }

    let uv_available = is_on_path("uv");
    let python_available = is_on_path("python3");

    let mut ready = 0;
    let mut total = 0;
    let mut needs_uv = false;
    let mut prewarmed = 0;

    for plugin in &plugins {
        total += 1;
        let name = &plugin.manifest.plugin.name;
        let entry_path = plugin.base_dir.join(&plugin.manifest.runtime.entry);
        if !entry_path.exists() {
            println!("  {name:<24} x entry not found: {}", entry_path.display());
            continue;
        }

        let requires = &plugin.manifest.runtime.requires;
        if requires.contains_key("uv") {
            needs_uv = true;
        }

        let is_lf = entry_path
            .extension()
            .map(|e| e == "lf")
            .unwrap_or(false);
        if !is_lf {
            println!("  {name:<24} ok (shell)");
            ready += 1;
            continue;
        }

        // Parse .lf to verify syntactic validity
        let source = match std::fs::read_to_string(&entry_path) {
            Ok(s) => s,
            Err(e) => {
                println!("  {name:<24} x cannot read: {e}");
                continue;
            }
        };
        let rs = match lf::parse(&source) {
            Ok(r) => r,
            Err(e) => {
                println!("  {name:<24} x parse error: {e:#}");
                continue;
            }
        };

        // Collect python bodies with PEP 723 headers for prewarming
        let pep723_bodies = collect_pep723_bodies(&rs);
        if pep723_bodies.is_empty() {
            println!("  {name:<24} ok (.lf, {} rules)", rs.rules.len());
            ready += 1;
            continue;
        }
        if !uv_available {
            println!(
                "  {name:<24} ! needs uv to resolve {} PEP 723 body(ies)",
                pep723_bodies.len()
            );
            continue;
        }

        let mut all_ok = true;
        for (i, body) in pep723_bodies.iter().enumerate() {
            match prewarm_uv(body) {
                Ok(_) => prewarmed += 1,
                Err(e) => {
                    println!(
                        "  {name:<24} x PEP 723 body #{}: {e:#}",
                        i + 1
                    );
                    all_ok = false;
                    break;
                }
            }
        }
        if all_ok {
            println!(
                "  {name:<24} ok (.lf, {} rules, {} uv env(s) cached)",
                rs.rules.len(),
                pep723_bodies.len()
            );
            ready += 1;
        }
    }

    println!();
    println!("  {ready}/{total} plugins ready, {prewarmed} uv env(s) warmed.");
    if needs_uv && !uv_available {
        println!();
        println!("  ! uv not on PATH — required by at least one plugin.");
        println!("    install: curl -LsSf https://astral.sh/uv/install.sh | sh");
        println!("    or:      brew install uv");
    }
    if !python_available {
        println!();
        println!("  ! python3 not on PATH — `python:` blocks will fail.");
    }
    Ok(())
}

fn is_on_path(cmd: &str) -> bool {
    Command::new(cmd)
        .arg("--version")
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status()
        .map(|s| s.success())
        .unwrap_or(false)
}

/// Walk the ruleset and collect every `python:` body that declares
/// PEP 723 inline dependencies. Includes bodies inside macro definitions
/// and inside `split` sub-chains.
fn collect_pep723_bodies(rs: &lf::RuleSet) -> Vec<String> {
    let mut out = Vec::new();
    for d in &rs.defines {
        walk_ops(&d.ops, &mut out);
    }
    for r in &rs.rules {
        walk_ops(&r.ops, &mut out);
    }
    out
}

fn walk_ops(ops: &[Op], out: &mut Vec<String>) {
    for op in ops {
        match op {
            Op::Python(body) => {
                if body
                    .lines()
                    .any(|l| l.trim_start().starts_with("# /// script"))
                {
                    out.push(body.clone());
                }
            }
            Op::Split { pre, post, .. } => {
                walk_ops(pre, out);
                walk_ops(post, out);
            }
            _ => {}
        }
    }
}

/// Trigger uv dep resolution by running the script with empty stdin.
/// uv caches resolved envs at `~/.cache/uv/`, so the first real invocation
/// hits a warm cache.
fn prewarm_uv(body: &str) -> Result<()> {
    let mut script = tempfile::Builder::new()
        .prefix("lowfat-doctor-")
        .suffix(".py")
        .tempfile()?;
    script.write_all(body.as_bytes())?;
    script.flush().ok();
    let path = script.path().to_str().unwrap().to_string();

    let mut child = Command::new("uv")
        .args(["run", "--script", &path])
        .stdin(Stdio::piped())
        .stdout(Stdio::null())
        .stderr(Stdio::piped())
        .spawn()?;
    // Empty stdin: many scripts will exit immediately on stdin.read(); deps
    // are resolved during uv's startup regardless of script behavior.
    drop(child.stdin.take());
    let output = child.wait_with_output()?;
    if !output.status.success() {
        // Non-zero exit from the script body itself is fine — what we care
        // about is whether uv could resolve the env. Distinguish by checking
        // stderr for uv-level errors vs. script tracebacks.
        let stderr = String::from_utf8_lossy(&output.stderr);
        if stderr.contains("error:") && !stderr.contains("Traceback") {
            anyhow::bail!("uv: {}", stderr.lines().next().unwrap_or("").trim());
        }
    }
    Ok(())
}

pub fn info(name: &str) -> Result<()> {
    let config = RunfConfig::resolve();
    let plugins = discover_plugins(&config.plugin_dir);

    let plugin = plugins
        .iter()
        .find(|p| p.manifest.plugin.name == name);

    match plugin {
        Some(p) => {
            let m = &p.manifest;
            println!("Plugin: {}", m.plugin.name);
            println!("  Version:     {}", m.plugin.version.as_deref().unwrap_or("?"));
            println!("  Description: {}", m.plugin.description.as_deref().unwrap_or("-"));
            println!("  Author:      {}", m.plugin.author.as_deref().unwrap_or("-"));
            println!("  Category:    {}", p.category);
            println!("  Entry:       {}", m.runtime.entry);
            println!("  Commands:    {}", m.plugin.commands.join(", "));
            println!("  Path:        {}", p.base_dir.display());
        }
        None => {
            eprintln!("lowfat: plugin not found: {name}");
        }
    }

    Ok(())
}

pub fn trust(name: &str) -> Result<()> {
    let config = RunfConfig::resolve();
    lowfat_plugin::security::trust_plugin(name, &config.home_dir)?;
    println!("lowfat: plugin '{name}' is now trusted");
    Ok(())
}

pub fn untrust(name: &str) -> Result<()> {
    let config = RunfConfig::resolve();
    lowfat_plugin::security::untrust_plugin(name, &config.home_dir)?;
    println!("lowfat: trust revoked for plugin '{name}'");
    Ok(())
}

pub fn new_plugin(name: &str, command: &str) -> Result<()> {
    let config = RunfConfig::resolve();

    // Create plugin directory: ~/.lowfat/plugins/<command>/<name>/
    let plugin_dir = config.plugin_dir.join(command).join(name);
    if plugin_dir.exists() {
        anyhow::bail!("plugin already exists: {}", plugin_dir.display());
    }
    std::fs::create_dir_all(&plugin_dir)?;

    // Write lowfat.toml manifest
    let manifest = format!(
        r#"[plugin]
name = "{name}"
commands = ["{command}"]

[runtime]
type = "shell"
entry = "filter.sh"
"#,
        name = name,
        command = command,
    );
    std::fs::write(plugin_dir.join("lowfat.toml"), manifest)?;

    // Write filter script
    std::fs::write(plugin_dir.join("filter.sh"), scaffold_shell())?;

    // Scaffold samples/ directory
    let samples_dir = plugin_dir.join("samples");
    std::fs::create_dir_all(&samples_dir)?;
    std::fs::write(
        samples_dir.join(format!("{command}-output-full.txt")),
        "# Paste real command output here.\n# Filename convention: <command>-<subcommand>-<level>.txt\n# Run: lowfat plugin bench <name>\n",
    )?;

    // Auto-trust the plugin
    lowfat_plugin::security::trust_plugin(name, &config.home_dir)?;

    println!("lowfat: created plugin '{name}'");
    println!("  {}", plugin_dir.display());
    println!("  edit: {}", plugin_dir.join("filter.sh").display());
    println!("  bench: lowfat plugin bench {name}");
    println!("  test: lowfat {command} <args>");
    Ok(())
}

fn scaffold_shell() -> String {
    r#"#!/bin/sh
# lowfat plugin — reads raw output from stdin, writes filtered output to stdout
# env: $LOWFAT_LEVEL (lite|full|ultra), $LOWFAT_COMMAND, $LOWFAT_SUBCOMMAND, $LOWFAT_ARGS, $LOWFAT_EXIT_CODE
#
# Level convention:
#   lite  — gentle trim, keep most output (~60 lines)
#   full  — balanced, strip noise (~30 lines)
#   ultra — summary only, minimal output (~10 lines)

LEVEL="${LOWFAT_LEVEL:-full}"
SUB="$LOWFAT_SUBCOMMAND"

case "$LEVEL" in
  lite)  head -n 60 ;;
  ultra) head -n 10 ;;
  *)     head -n 30 ;;
esac
"#
    .to_string()
}

pub fn bench(name: &str) -> Result<()> {
    let config = RunfConfig::resolve();
    let plugins = discover_plugins(&config.plugin_dir);

    let plugin = plugins
        .iter()
        .find(|p| p.manifest.plugin.name == name);

    let plugin = match plugin {
        Some(p) => p,
        None => {
            // Also check repo plugins/ directory
            anyhow::bail!("plugin not found: {name} (install it to ~/.lowfat/plugins/ first)");
        }
    };

    let samples_dir = plugin.base_dir.join("samples");
    if !samples_dir.is_dir() {
        anyhow::bail!("no samples/ directory in plugin '{name}' — add .txt files with sample command output");
    }

    let mut entries: Vec<_> = std::fs::read_dir(&samples_dir)?
        .filter_map(|e| e.ok())
        .filter(|e| e.path().extension().map_or(false, |ext| ext == "txt"))
        .collect();
    entries.sort_by_key(|e| e.path());

    if entries.is_empty() {
        anyhow::bail!("no .txt sample files in {}", samples_dir.display());
    }

    // Build the process filter
    let process_filter = lowfat_runner::process::ProcessFilter {
        info: lowfat_plugin::plugin::PluginInfo {
            name: plugin.manifest.plugin.name.clone(),
            version: plugin.manifest.plugin.version.clone().unwrap_or_default(),
            commands: plugin.manifest.plugin.commands.clone(),
            subcommands: plugin.manifest.plugin.subcommands.clone().unwrap_or_default(),
        },
        entry: plugin.base_dir.join(&plugin.manifest.runtime.entry),
        base_dir: plugin.base_dir.clone(),
    };

    println!("Benchmark: {name}");
    println!();

    let mut total_raw = 0usize;
    let mut total_filtered = 0usize;

    for entry in &entries {
        let path = entry.path();
        let sample_name = path.file_stem().unwrap_or_default().to_string_lossy();

        // Parse sample name: "git-status-full.txt" → command=git, subcommand=status, level=full
        let parts: Vec<&str> = sample_name.split('-').collect();
        let (command, subcommand, level_str) = match parts.len() {
            1 => (parts[0], "", "full"),
            2 => (parts[0], parts[1], "full"),
            _ => (parts[0], parts[1], parts[parts.len() - 1]),
        };

        let level = match level_str {
            "lite" => lowfat_core::level::Level::Lite,
            "ultra" => lowfat_core::level::Level::Ultra,
            _ => lowfat_core::level::Level::Full,
        };

        let raw = std::fs::read_to_string(&path)?;
        let raw_tokens = lowfat_core::tokens::estimate_tokens(&raw);

        let input = lowfat_plugin::plugin::FilterInput {
            raw: raw.clone(),
            command: command.to_string(),
            subcommand: subcommand.to_string(),
            args: vec![],
            level,
            head_limit: level.head_limit(40),
            exit_code: 0,
        };

        use lowfat_plugin::plugin::FilterPlugin;
        let result = process_filter.filter(&input)?;
        let filtered_tokens = lowfat_core::tokens::estimate_tokens(&result.text);
        let pct = if raw_tokens > 0 {
            (1.0 - filtered_tokens as f64 / raw_tokens as f64) * 100.0
        } else {
            0.0
        };

        total_raw += raw_tokens;
        total_filtered += filtered_tokens;

        println!(
            "  {:<30} {:>6}{:>6} tokens  ({:>-3.0}%)",
            format!("{sample_name} ({level})"), raw_tokens, filtered_tokens, -pct
        );
    }

    if total_raw > 0 {
        let total_pct = (1.0 - total_filtered as f64 / total_raw as f64) * 100.0;
        println!();
        println!(
            "  {:<30} {:>6}{:>6} tokens  ({:>-3.0}%)",
            "TOTAL", total_raw, total_filtered, -total_pct
        );
    }

    Ok(())
}