tokf 0.2.33

Config-driven CLI tool that compresses command output before it reaches an LLM context
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
use std::path::Path;

use tokf::baseline;
use tokf::config;
use tokf::filter;
use tokf::history;
use tokf::history::OutputConfig;
use tokf::hook;
use tokf::rewrite;
use tokf::runner;
use tokf::skill;
use tokf::telemetry;

use crate::resolve;
use crate::{Cli, HookFormat, HookTool};

pub fn or_exit(r: anyhow::Result<i32>) -> i32 {
    r.unwrap_or_else(|e| {
        eprintln!("[tokf] error: {e:#}");
        1
    })
}

// NOTE: cmd_run integrates command resolution, execution, output rendering, tracking,
// history recording, and telemetry. Splitting would require threading 6+ values through helpers.
// Approved to exceed the 60-line limit.
#[allow(clippy::too_many_lines)]
pub fn cmd_run(
    command_args: &[String],
    baseline_pipe: Option<&str>,
    prefer_less: bool,
    cli: &Cli,
    reporter: &dyn telemetry::TelemetryReporter,
) -> anyhow::Result<i32> {
    let filter_match = if cli.no_filter {
        None
    } else {
        resolve::find_filter(command_args, cli.verbose, cli.no_cache)?
    };

    let words_consumed = filter_match.as_ref().map_or(0, |m| m.words_consumed);
    let remaining_args: Vec<String> = if words_consumed > 0 {
        command_args[words_consumed..].to_vec()
    } else if command_args.len() > 1 {
        command_args[1..].to_vec()
    } else {
        vec![]
    };

    let passthrough = filter_match
        .as_ref()
        .is_some_and(|m| m.config.should_passthrough(&remaining_args));
    if passthrough && cli.verbose {
        eprintln!("[tokf] passthrough: user args match passthrough_args, skipping filter");
    }
    let filter_cfg = if passthrough {
        None
    } else {
        filter_match.as_ref().map(|m| &m.config)
    };
    let cmd_result =
        resolve::run_command(filter_cfg, words_consumed, command_args, &remaining_args)?;

    let filter_match = if passthrough { None } else { filter_match };
    let Some(filter_match) = filter_match else {
        if prefer_less && cli.verbose {
            eprintln!("[tokf] --prefer-less has no effect: no matching filter found");
        }
        let raw_len = cmd_result.combined.len();
        let input_bytes = match baseline_pipe {
            Some(pipe_cmd) => baseline::compute(&cmd_result.combined, pipe_cmd),
            None => raw_len,
        };
        let mask = !cli.no_mask_exit_code && cmd_result.exit_code != 0;
        if mask {
            println!("Error: Exit code {}", cmd_result.exit_code);
        }
        if !cmd_result.combined.is_empty() {
            println!("{}", cmd_result.combined);
        }
        // filter_time_ms = 0: no filter was applied, not 0ms of filtering.
        // Passthrough commands are not recorded to history: raw == filtered would
        // waste storage and add noise with nothing useful to compare.
        // output_bytes = raw_len: what tokf actually printed (full raw output).
        resolve::record_run(
            command_args,
            None,
            None,
            input_bytes,
            raw_len,
            raw_len,
            0,
            cmd_result.exit_code,
            false,
        );
        resolve::try_auto_sync();
        reporter.report(&telemetry::TelemetryEvent::new(
            None,
            command_args.join(" "),
            input_bytes,
            raw_len,
            raw_len,
            &cmd_result.combined,
            &cmd_result.combined,
            std::time::Duration::ZERO,
            cmd_result.exit_code,
        ));
        if cli.no_mask_exit_code {
            return Ok(cmd_result.exit_code);
        }
        return Ok(0);
    };

    // Phase B: resolve deferred output-pattern variants using the already-discovered
    // filter list (no second discovery call needed).
    let (cfg, filter_hash) =
        resolve::resolve_phase_b(filter_match, &cmd_result.combined, cli.verbose);

    // Compute piped output once: when prefer_less is active we need the full text
    // for comparison, otherwise just the byte count for tracking.
    let (input_bytes, piped_text) = match baseline_pipe {
        Some(pipe_cmd) if prefer_less => {
            let text = baseline::compute_output(&cmd_result.combined, pipe_cmd);
            let bytes = text.as_ref().map_or(cmd_result.combined.len(), String::len);
            (bytes, text)
        }
        Some(pipe_cmd) => (baseline::compute(&cmd_result.combined, pipe_cmd), None),
        None => (cmd_result.combined.len(), None),
    };

    let start = std::time::Instant::now();
    let filter_opts = filter::FilterOptions {
        preserve_color: cli.preserve_color,
    };
    let filtered = filter::apply(&cfg, &cmd_result, &remaining_args, &filter_opts);
    let elapsed = start.elapsed();

    if cli.timing {
        eprintln!("[tokf] filter took {:.1}ms", elapsed.as_secs_f64() * 1000.0);
    }

    // --prefer-less: compare filtered output with cached piped output, use whichever is smaller.
    let (final_output, output_bytes, pipe_override) =
        if let Some(piped) = piped_text.filter(|t| t.len() < filtered.output.len()) {
            if cli.verbose {
                eprintln!(
                    "[tokf] prefer-less: pipe output ({} bytes) < filtered ({} bytes), using pipe",
                    piped.len(),
                    filtered.output.len()
                );
            }
            let len = piped.len();
            (piped, len, true)
        } else {
            let len = filtered.output.len();
            (filtered.output, len, false)
        };

    let filter_name = cfg.command.first();
    let command_str = command_args.join(" ");
    let raw_bytes = cmd_result.combined.len();

    if cli.verbose {
        eprintln!(
            "[tokf] accounting: raw={raw_bytes}B baseline={input_bytes}B filtered={output_bytes}B"
        );
    }

    resolve::record_run(
        command_args,
        Some(filter_name),
        Some(&filter_hash),
        input_bytes,
        output_bytes,
        raw_bytes,
        elapsed.as_millis(),
        cmd_result.exit_code,
        pipe_override,
    );
    resolve::try_auto_sync();

    // Detect whether to show the history hint:
    //   - filter author opted in via `show_history_hint = true`, or
    //   - the same command was re-run (LLM confusion signal: it didn't act on
    //     the previous filtered output and is asking again).
    // Check the DB before recording so we compare against the *previous* run.
    let show_hint = cfg.show_history_hint || history::try_was_recently_run(&command_str);

    let history_id = history::try_record(
        &command_str,
        filter_name,
        &cmd_result.combined,
        &final_output,
        cmd_result.exit_code,
    );

    let output_cfg = {
        let cwd = std::env::current_dir().unwrap_or_default();
        let project_root = history::project_root_for(&cwd);
        OutputConfig::load(Some(&project_root))
    };

    let mask = !cli.no_mask_exit_code && cmd_result.exit_code != 0;
    if mask {
        println!("Error: Exit code {}", cmd_result.exit_code);
    }
    if !final_output.is_empty() {
        if output_cfg.show_indicator {
            println!("🗜️ {final_output}");
        } else {
            println!("{final_output}");
        }
    }

    if show_hint && let Some(id) = history_id {
        println!("🗜️ compressed — run `tokf raw {id}` for full output");
    }

    reporter.report(&telemetry::TelemetryEvent::new(
        Some(filter_name.to_string()),
        command_str,
        input_bytes,
        output_bytes,
        raw_bytes,
        &cmd_result.combined,
        &final_output,
        elapsed,
        cmd_result.exit_code,
    ));

    if cli.no_mask_exit_code {
        Ok(cmd_result.exit_code)
    } else {
        Ok(0)
    }
}

pub fn cmd_check(filter_path: &Path) -> i32 {
    match config::try_load_filter(filter_path) {
        Ok(Some(cfg)) => {
            eprintln!(
                "[tokf] {} is valid (command: \"{}\")",
                filter_path.display(),
                cfg.command.first()
            );
            0
        }
        Ok(None) => {
            eprintln!("[tokf] file not found: {}", filter_path.display());
            1
        }
        Err(e) => {
            eprintln!("[tokf] error: {e:#}");
            1
        }
    }
}

pub fn cmd_test(
    filter_path: &Path,
    fixture_path: &Path,
    exit_code: i32,
    cli: &Cli,
) -> anyhow::Result<i32> {
    let cfg = config::try_load_filter(filter_path)?
        .ok_or_else(|| anyhow::anyhow!("filter not found: {}", filter_path.display()))?;

    let fixture = std::fs::read_to_string(fixture_path)
        .map_err(|e| anyhow::anyhow!("failed to read fixture: {}: {e}", fixture_path.display()))?;
    let combined = fixture.trim_end().to_string();

    let cmd_result = runner::CommandResult {
        stdout: String::new(),
        stderr: String::new(),
        exit_code,
        combined,
    };

    let start = std::time::Instant::now();
    let filter_opts = filter::FilterOptions {
        preserve_color: cli.preserve_color,
    };
    let filtered = filter::apply(&cfg, &cmd_result, &[], &filter_opts);
    let elapsed = start.elapsed();

    if cli.timing {
        eprintln!("[tokf] filter took {:.1}ms", elapsed.as_secs_f64() * 1000.0);
    }

    // tokf test always writes to stdout — it's a debugging tool that always
    // exits 0, not a hook-invoked path subject to the stderr-on-failure routing.
    if !filtered.output.is_empty() {
        println!("{}", filtered.output);
    }

    Ok(0)
}

// Note: cmd_ls and cmd_which always use the cache. The --no-cache flag
// only affects `tokf run`. Pass --no-cache to `tokf run` if you need uncached resolution.
pub fn cmd_ls(verbose: bool) -> i32 {
    let Ok(filters) = resolve::discover_filters(false) else {
        eprintln!("[tokf] error: failed to discover filters");
        return 1;
    };

    for filter in &filters {
        // Display: relative path without .toml extension  →  command  (description)
        let display_name = filter
            .relative_path
            .with_extension("")
            .display()
            .to_string();
        let desc_suffix = filter
            .config
            .description
            .as_deref()
            .map_or(String::new(), |d| format!("  ({d})"));
        println!(
            "{display_name}  \u{2192}  {}{desc_suffix}",
            filter.config.command.first()
        );

        if verbose {
            eprintln!(
                "[tokf]   source: {}  [{}]",
                filter.source_path.display(),
                filter.priority_label()
            );
            let patterns = filter.config.command.patterns();
            if patterns.len() > 1 {
                for p in patterns {
                    eprintln!("[tokf]     pattern: \"{p}\"");
                }
            }
        }
    }

    0
}

pub fn cmd_which(command: &str, verbose: bool) -> i32 {
    let Ok(filters) = resolve::discover_filters(false) else {
        eprintln!("[tokf] error: failed to discover filters");
        return 1;
    };

    let words: Vec<&str> = command.split_whitespace().collect();
    let cwd = std::env::current_dir().unwrap_or_default();

    for filter in &filters {
        if filter.matches(&words).is_some() {
            let display_name = filter
                .relative_path
                .with_extension("")
                .display()
                .to_string();

            let variant_info = if filter.config.variant.is_empty() {
                String::new()
            } else {
                let res =
                    config::variant::resolve_variants(&filter.config, &filters, &cwd, verbose);
                let resolved = res.config.command.first().to_string();
                if resolved != filter.config.command.first() {
                    format!(" -> variant: \"{resolved}\"")
                } else if res.output_variants.is_empty() {
                    format!(
                        " ({} variant(s), none matched by file)",
                        filter.config.variant.len()
                    )
                } else {
                    let names: Vec<&str> = res
                        .output_variants
                        .iter()
                        .map(|v| v.name.as_str())
                        .collect();
                    format!(
                        " ({} variant(s), {} deferred to output-pattern: {})",
                        filter.config.variant.len(),
                        res.output_variants.len(),
                        names.join(", ")
                    )
                }
            };
            println!(
                "{display_name}  [{}]  command: \"{}\"{variant_info}",
                filter.priority_label(),
                filter.config.command.first()
            );
            if verbose {
                eprintln!("[tokf] source: {}", filter.source_path.display());
            }
            return 0;
        }
    }

    eprintln!("[tokf] no filter found for \"{command}\"");
    1
}

pub fn cmd_rewrite(command: &str, verbose: bool) -> i32 {
    let result = rewrite::rewrite(command, verbose);
    println!("{result}");
    0
}

pub fn cmd_skill_install(global: bool) -> i32 {
    match skill::install(global) {
        Ok(()) => 0,
        Err(e) => {
            eprintln!("[tokf] error: {e:#}");
            1
        }
    }
}

pub fn cmd_hook_handle(format: &HookFormat) -> i32 {
    // Return values (true = rewritten, false = pass-through) are intentionally
    // discarded: the hook must always exit 0 so it never blocks the IDE's command.
    match format {
        HookFormat::ClaudeCode => {
            hook::handle();
        }
        HookFormat::Gemini => {
            hook::handle_gemini();
        }
        HookFormat::Cursor => {
            hook::handle_cursor();
        }
    }
    0
}

pub fn cmd_hook_install(
    global: bool,
    tool: &HookTool,
    path: Option<&Path>,
    install_context: bool,
) -> i32 {
    let tokf_bin = path.map_or_else(|| "tokf".to_string(), |p| p.display().to_string());
    let result = match tool {
        HookTool::ClaudeCode => hook::install(global, &tokf_bin, install_context),
        HookTool::OpenCode => hook::opencode::install(global, &tokf_bin),
        HookTool::Codex => hook::codex::install(global),
        HookTool::GeminiCli => hook::gemini::install(global, &tokf_bin, install_context),
        HookTool::Cursor => hook::cursor::install(global, &tokf_bin, install_context),
        HookTool::Cline => hook::cline::install(global),
        HookTool::Windsurf => hook::windsurf::install(global),
        HookTool::Copilot => hook::copilot::install(global),
        HookTool::Aider => hook::aider::install(global),
    };
    match result {
        Ok(()) => 0,
        Err(e) => {
            eprintln!("[tokf] hook install failed: {e:#}");
            1
        }
    }
}