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
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
mod auth_cmd;
#[cfg(feature = "stdlib-publish")]
mod backfill_cmd;
mod cache_cmd;
mod commands;
mod completions_cmd;
mod config_cmd;
mod discover_cmd;
mod doctor_cmd;
mod eject_cmd;
mod gain;
mod gain_render;
mod generic;
mod history_cmd;
mod info_cmd;
mod install_cmd;
mod output;
mod publish_cmd;
#[cfg(feature = "stdlib-publish")]
mod publish_stdlib_cmd;
mod remote_cmd;
mod resolve;
mod search_cmd;
mod setup_cmd;
mod shell;
mod show_cmd;
mod sync_cmd;
mod telemetry_cmd;
// pub(crate): accessed by install_cmd::run_verify
pub(crate) mod verify_cmd;
use std::path::Path;
use clap::{Parser, Subcommand};
use commands::{HistoryAction, HookAction};
use tokf::telemetry;
#[derive(Parser)]
#[command(
name = "tokf",
version,
about = "Token filter — compress command output for LLM context"
)]
#[allow(clippy::struct_excessive_bools)] // CLI flags are naturally booleans
pub(crate) struct Cli {
/// Show how long filtering took
#[arg(long, global = true)]
pub timing: bool,
/// Skip filtering, pass output through raw
#[arg(long, global = true)]
pub no_filter: bool,
/// Show filter resolution details
#[arg(short, long, global = true)]
pub verbose: bool,
/// Bypass the binary config cache for this invocation
#[arg(long, global = true)]
pub no_cache: bool,
/// Disable exit-code masking. By default tokf exits 0 and prepends
/// "Error: Exit code N" to output when the underlying command fails.
/// This flag restores real exit-code propagation.
#[arg(long, global = true)]
pub no_mask_exit_code: bool,
/// Preserve ANSI color codes in filtered output. Internally strips ANSI
/// for pattern matching but restores original colored lines in the result.
/// Note: this is not `--color=always/never/auto` — it controls passthrough
/// of the child command's existing ANSI codes through the filter pipeline.
#[arg(long, global = true, env = "TOKF_PRESERVE_COLOR")]
pub preserve_color: bool,
/// Export metrics via OpenTelemetry OTLP (requires --features otel)
#[arg(long, global = true)]
otel_export: bool,
#[command(subcommand)]
command: Commands,
}
#[derive(Subcommand)]
enum Commands {
/// Run a command and filter its output
Run {
/// Pipe command for fair accounting (set by rewrite when stripping pipes)
#[arg(long)]
baseline_pipe: Option<String>,
/// Use whichever output is smaller: filtered or piped (no-op without --baseline-pipe)
#[arg(long)]
prefer_less: bool,
#[arg(trailing_var_arg = true, required = true)]
command_args: Vec<String>,
},
/// Generate shell completion scripts
Completions {
/// Target shell (bash, zsh, fish, powershell, elvish, nushell)
shell: completions_cmd::ShellChoice,
},
/// Validate a filter TOML file
Check {
/// Path to the filter file
filter_path: String,
},
/// Apply a filter to a fixture file (formerly `test`)
#[command(alias = "test-filter")]
Apply {
/// Path to the filter file
filter_path: String,
/// Path to the fixture file
fixture_path: String,
/// Simulated exit code for branch selection
#[arg(long, default_value_t = 0)]
exit_code: i32,
},
/// List available filters
Ls,
/// Rewrite a command string (apply filter-derived rules)
Rewrite {
/// The command string to rewrite
command: String,
},
/// Show which filter would be used for a command
Which {
/// The command string to look up (e.g. "git push origin main")
command: String,
},
/// Show the TOML source of an active filter
Show {
/// Filter relative path without extension (e.g. "git/push")
filter: String,
/// Print the SHA-256 content hash of the filter (for identity verification or change detection)
#[arg(long)]
hash: bool,
},
/// Copy a filter to your local or global config for customization
Eject {
/// Filter relative path without extension (e.g. "cargo/build")
filter: String,
/// Eject to global config dir instead of project-local .tokf/
#[arg(long)]
global: bool,
},
/// Claude Code hook management
Hook {
#[command(subcommand)]
action: HookAction,
},
/// Install the Claude Code filter-authoring skill
Skill {
#[command(subcommand)]
action: SkillAction,
},
/// Manage the filter resolution cache
Cache {
#[command(subcommand)]
action: cache_cmd::CacheAction,
},
/// View and modify tokf configuration
Config {
#[command(subcommand)]
action: config_cmd::ConfigAction,
},
/// Show token savings statistics
Gain {
/// Show daily breakdown
#[arg(long)]
daily: bool,
/// Show breakdown by filter
#[arg(long, name = "by-filter")]
by_filter: bool,
/// Output as JSON
#[arg(long)]
json: bool,
/// Query remote server stats instead of local database
#[arg(long)]
remote: bool,
/// Number of top filters to show in the summary view (default: 10)
#[arg(long, default_value_t = 10)]
top: usize,
/// Disable colored output (also respects the `NO_COLOR` environment variable)
#[arg(long)]
no_color: bool,
},
/// Manage filtered output history
History {
#[command(subcommand)]
action: HistoryAction,
},
/// Print raw (unfiltered) output — `tokf raw last` or `tokf raw <id>`
Raw {
/// "last" for most recent, or a numeric entry ID
target: String,
},
/// Run declarative test suites for filters
Verify {
/// Filter name to test (e.g. "cargo/build"). Omit to run all.
filter: Option<String>,
/// List available test suites without running them
#[arg(long)]
list: bool,
/// Output results as JSON
#[arg(long)]
json: bool,
/// Fail if any filters have no test suite
#[arg(long)]
require_all: bool,
/// Restrict to a single filter scope (project, global, or stdlib)
#[arg(long, value_enum)]
scope: Option<verify_cmd::VerifyScope>,
/// Run safety checks (detect prompt injection, shell injection, hidden unicode)
#[arg(long)]
safety: bool,
},
/// Show system paths, database locations, and filter counts
Info {
/// Output as JSON
#[arg(long)]
json: bool,
},
/// Authenticate with the tokf server (credentials stored in OS keyring)
Auth {
#[command(subcommand)]
action: AuthAction,
},
/// Register this machine and manage remote sync settings
Remote {
#[command(subcommand)]
action: RemoteAction,
},
/// Publish a local filter to the community registry
Publish {
/// Filter name to publish (e.g. "git/my-filter")
filter: String,
/// Preview what would be published without uploading
#[arg(long)]
dry_run: bool,
/// Replace the test suite for an already-published filter (author-only)
#[arg(long)]
update_tests: bool,
},
/// Search the community filter registry
Search {
/// Maximum number of results to return
#[arg(long, short = 'n', default_value_t = 20)]
limit: usize,
/// Output results as JSON
#[arg(long)]
json: bool,
/// Search query (matches command pattern)
#[arg(trailing_var_arg = true, required = true)]
query: Vec<String>,
},
/// Sync local usage data to the remote server
Sync {
/// Show last sync time and count of pending events
#[arg(long)]
status: bool,
},
/// Publish all stdlib filters to the registry (CI only)
#[cfg(feature = "stdlib-publish")]
PublishStdlib {
/// Registry base URL
#[arg(long, env = "TOKF_REGISTRY_URL")]
registry_url: String,
/// Service token for authentication
#[arg(long, env = "TOKF_SERVICE_TOKEN")]
token: String,
/// Preview the payload without uploading
#[arg(long)]
dry_run: bool,
},
/// Backfill filter version history from git tags (CI only)
#[cfg(feature = "stdlib-publish")]
BackfillVersions {
/// Registry base URL
#[arg(long, env = "TOKF_REGISTRY_URL")]
registry_url: String,
/// Service token for authentication
#[arg(long, env = "TOKF_SERVICE_TOKEN")]
token: String,
/// Print computed timeline without posting to registry
#[arg(long)]
dry_run: bool,
},
/// Telemetry configuration and diagnostics
Telemetry {
#[command(subcommand)]
action: TelemetryAction,
},
/// Detect filters that may be causing agent confusion (post-hoc analysis of tracking.db)
Doctor(commands::DoctorArgs),
/// Find missed token savings in Claude Code sessions
Discover {
/// Project path to scan (defaults to current directory)
#[arg(long, conflicts_with_all = ["all", "session"])]
project: Option<String>,
/// Scan all projects
#[arg(long, conflicts_with = "session")]
all: bool,
/// Path to a single session file
#[arg(long)]
session: Option<String>,
/// Only scan sessions modified within this window (e.g. 7d, 24h)
#[arg(long)]
since: Option<String>,
/// Maximum number of results to show (0 = unlimited, default: 20)
#[arg(long, default_value_t = 20)]
limit: usize,
/// Output as JSON
#[arg(long)]
json: bool,
/// Also show commands that already have a matching filter
#[arg(long)]
include_filtered: bool,
},
/// Run a command and show only errors/warnings
Err {
/// Lines of context around each error
#[arg(short = 'C', long, default_value_t = 3)]
context: usize,
/// Pipe command for fair baseline accounting
#[arg(long)]
baseline_pipe: Option<String>,
#[arg(trailing_var_arg = true, required = true)]
command_args: Vec<String>,
},
/// Run a test command and show only failures
Test {
/// Lines of context around each failure
#[arg(short = 'C', long, default_value_t = 5)]
context: usize,
/// Pipe command for fair baseline accounting
#[arg(long)]
baseline_pipe: Option<String>,
#[arg(trailing_var_arg = true, required = true)]
command_args: Vec<String>,
},
/// Run a command and produce a heuristic summary
Summary {
/// Maximum lines in the summary output
#[arg(long, default_value_t = 30)]
max_lines: usize,
/// Pipe command for fair baseline accounting
#[arg(long)]
baseline_pipe: Option<String>,
#[arg(trailing_var_arg = true, required = true)]
command_args: Vec<String>,
},
/// Detect installed AI tools and install hooks interactively
Setup {
/// Re-run setup even if already completed
#[arg(long, alias = "renew")]
refresh: bool,
},
/// Install a filter from the community registry
Install {
/// Filter hash (64 hex chars) or command pattern to search for
filter: String,
/// Install to project-local .tokf/filters/ instead of global config
#[arg(long)]
local: bool,
/// Overwrite an existing filter at the same path
#[arg(long)]
force: bool,
/// Preview what would be installed without writing files
#[arg(long)]
dry_run: bool,
/// Skip confirmation prompts (Lua filters still emit an audit warning)
#[arg(long, short = 'y')]
yes: bool,
},
}
#[derive(Subcommand)]
enum TelemetryAction {
/// Show telemetry configuration and connection status
Status {
/// Test connectivity to the OTLP endpoint
#[arg(long)]
check: bool,
},
}
#[derive(Subcommand)]
enum SkillAction {
/// Install skill files to .claude/skills/tokf-filter/ (project-local or global)
Install {
/// Install globally (~/.claude/skills/) instead of project-local (.claude/skills/)
#[arg(long)]
global: bool,
},
}
#[derive(Subcommand)]
enum AuthAction {
/// Log in via GitHub device flow (opens browser, stores token in OS keyring)
Login,
/// Log out and remove stored credentials (keyring token + config metadata)
Logout,
/// Show current authentication status (username, server URL)
Status,
/// Permanently delete your account (requires confirmation)
DeleteAccount,
}
#[derive(Subcommand)]
enum RemoteAction {
/// Register this machine with the tokf server for remote sync
Setup,
/// Show remote sync registration state
Status,
/// Sync local usage events to the remote server
Sync,
/// Backfill filter hashes for past events recorded before hash tracking was added
Backfill,
}
// Telemetry init + subcommand dispatch + shutdown added lines — approved to exceed 60-line limit.
#[allow(clippy::too_many_lines)]
fn main() {
use commands::{
cmd_apply, cmd_check, cmd_hook_handle, cmd_hook_install, cmd_ls, cmd_rewrite, cmd_run,
cmd_skill_install, cmd_which, or_exit,
};
tokf::paths::init_from_env();
#[cfg(feature = "test-keyring")]
tokf::auth::credentials::use_mock_keyring();
// Pre-clap shell mode detection.
//
// Task runners (make, just) invoke their shell as `$SHELL -c 'recipe_line'`.
// When tokf is set as the shell, we intercept `-c` (and variants like `-cu`,
// `-ec`) before clap parsing — clap would reject them as unknown flags.
let raw_args: Vec<String> = std::env::args().collect();
if raw_args.len() >= 2 && shell::is_shell_flag(&raw_args[1]) {
if raw_args.len() < 3 {
eprintln!("[tokf] shell mode requires a command argument");
std::process::exit(1);
}
let exit_code = if raw_args.len() == 3 {
// String mode: task runner sends `$SHELL -c 'recipe line'`
shell::cmd_shell(&raw_args[1], &raw_args[2])
} else {
// Argv mode: shim sends `tokf -c git status "$@"`
shell::cmd_shell_argv(&raw_args[1], &raw_args[2..])
};
std::process::exit(exit_code);
}
let cli = Cli::parse();
let reporter = telemetry::init(cli.otel_export);
if cli.verbose {
match reporter.endpoint_description() {
Some(ref desc) => eprintln!("[tokf] telemetry: enabled (endpoint: {desc})"),
None if cli.otel_export => {
eprintln!(
"[tokf] telemetry: disabled or unavailable (feature not compiled, or initialization failed)"
);
}
None => {}
}
}
let exit_code = match &cli.command {
Commands::Run {
command_args,
baseline_pipe,
prefer_less,
} => or_exit(cmd_run(
command_args,
baseline_pipe.as_deref(),
*prefer_less,
&cli,
reporter.as_ref(),
)),
Commands::Completions { shell } => completions_cmd::cmd_completions(*shell),
Commands::Check { filter_path } => cmd_check(Path::new(filter_path)),
Commands::Apply {
filter_path,
fixture_path,
exit_code,
} => or_exit(cmd_apply(
Path::new(filter_path),
Path::new(fixture_path),
*exit_code,
&cli,
)),
Commands::Ls => cmd_ls(cli.verbose),
Commands::Rewrite { command } => cmd_rewrite(command, cli.verbose),
Commands::Which { command } => cmd_which(command, cli.verbose),
Commands::Show { filter, hash } => show_cmd::cmd_show(filter, *hash),
Commands::Eject { filter, global } => eject_cmd::cmd_eject(filter, *global, cli.no_cache),
Commands::Hook { action } => match action {
HookAction::Handle { format } => cmd_hook_handle(format),
HookAction::Install {
global,
tool,
path,
no_context,
} => cmd_hook_install(*global, tool, path.as_deref(), !no_context),
},
Commands::Skill { action } => match action {
SkillAction::Install { global } => cmd_skill_install(*global),
},
Commands::Cache { action } => cache_cmd::run_cache_action(action),
Commands::Config { action } => config_cmd::run_config_action(action),
Commands::Gain {
daily,
by_filter,
json,
remote,
top,
no_color,
} => {
if *remote {
gain::cmd_gain_remote(*daily, *by_filter, *json, *top, *no_color)
} else {
gain::cmd_gain(*daily, *by_filter, *json, *top, *no_color)
}
}
Commands::Verify {
filter,
list,
json,
require_all,
scope,
safety,
} => verify_cmd::cmd_verify(
filter.as_deref(),
*list,
*json,
*require_all,
scope.as_ref(),
*safety,
),
Commands::Info { json } => info_cmd::cmd_info(*json),
Commands::Auth { action } => or_exit(match action {
AuthAction::Login => auth_cmd::cmd_auth_login(),
AuthAction::Logout => auth_cmd::cmd_auth_logout(),
AuthAction::Status => auth_cmd::cmd_auth_status(),
AuthAction::DeleteAccount => auth_cmd::cmd_auth_delete_account(),
}),
Commands::Remote { action } => or_exit(match action {
RemoteAction::Setup => remote_cmd::cmd_remote_setup(),
RemoteAction::Status => remote_cmd::cmd_remote_status(),
RemoteAction::Sync => remote_cmd::cmd_remote_sync(),
RemoteAction::Backfill => remote_cmd::cmd_remote_backfill(cli.no_cache),
}),
Commands::History { action } => or_exit(match action {
HistoryAction::List { limit, all } => history_cmd::cmd_history_list(*limit, *all),
HistoryAction::Show { id, raw } => history_cmd::cmd_history_show(*id, *raw),
HistoryAction::Last { raw, all } => history_cmd::cmd_history_last(*raw, *all),
HistoryAction::Search { query, limit, all } => {
history_cmd::cmd_history_search(query, *limit, *all)
}
HistoryAction::Clear { all } => history_cmd::cmd_history_clear(*all),
}),
Commands::Raw { target } => or_exit(if target == "last" {
history_cmd::cmd_history_last(true, false)
} else if let Ok(id) = target.parse::<i64>() {
history_cmd::cmd_history_show(id, true)
} else {
eprintln!("[tokf] expected `last` or a numeric ID, got: {target}");
Ok(1)
}),
Commands::Sync { status } => or_exit(sync_cmd::cmd_sync(*status)),
Commands::Publish {
filter,
dry_run,
update_tests,
} => publish_cmd::cmd_publish(filter, *dry_run, *update_tests),
Commands::Search { query, limit, json } => {
let joined = query.join(" ");
search_cmd::cmd_search(&joined, *limit, *json)
}
#[cfg(feature = "stdlib-publish")]
Commands::PublishStdlib {
registry_url,
token,
dry_run,
} => publish_stdlib_cmd::cmd_publish_stdlib(registry_url, token, *dry_run),
#[cfg(feature = "stdlib-publish")]
Commands::BackfillVersions {
registry_url,
token,
dry_run,
} => backfill_cmd::cmd_backfill_versions(registry_url, token, *dry_run),
Commands::Telemetry { action } => or_exit(match action {
TelemetryAction::Status { check } => {
telemetry_cmd::cmd_telemetry_status(*check, cli.verbose)
}
}),
Commands::Discover {
project,
all,
session,
since,
limit,
json,
include_filtered,
} => or_exit(discover_cmd::cmd_discover(&discover_cmd::DiscoverOpts {
project: project.as_deref(),
all: *all,
session: session.as_deref(),
since: since.as_deref(),
limit: *limit,
json: *json,
no_cache: cli.no_cache,
include_filtered: *include_filtered,
})),
Commands::Doctor(args) => doctor_cmd::cmd_doctor(&doctor_cmd::DoctorCliOpts {
burst_threshold: args.burst_threshold,
window_secs: args.window,
project: args.project.as_deref(),
all_projects: args.all,
include_noise: args.include_noise,
filter: args.filter.as_deref(),
sort: args.sort.into(),
json: args.json,
no_color: args.no_color,
no_cache: cli.no_cache,
}),
Commands::Err {
context,
baseline_pipe,
command_args,
} => or_exit(generic::cmd_generic_run(
command_args,
baseline_pipe.as_deref(),
"_builtin/err",
&cli,
|text, ec| generic::err::extract_errors(text, ec, *context),
)),
Commands::Test {
context,
baseline_pipe,
command_args,
} => or_exit(generic::cmd_generic_run(
command_args,
baseline_pipe.as_deref(),
"_builtin/test",
&cli,
|text, ec| generic::test_run::extract_test_failures(text, ec, *context),
)),
Commands::Summary {
max_lines,
baseline_pipe,
command_args,
} => or_exit(generic::cmd_generic_run(
command_args,
baseline_pipe.as_deref(),
"_builtin/summary",
&cli,
|text, ec| generic::summary::summarize(text, ec, *max_lines),
)),
Commands::Setup { refresh } => setup_cmd::cmd_setup(*refresh),
Commands::Install {
filter,
local,
force,
dry_run,
yes,
} => install_cmd::cmd_install(filter, *local, *force, *dry_run, *yes),
};
let flushed = reporter.shutdown();
if cli.verbose && reporter.endpoint_description().is_some() {
if flushed {
eprintln!("[tokf] telemetry: metrics exported");
} else {
eprintln!("[tokf] telemetry: export timed out — events are in local DB");
}
}
std::process::exit(exit_code);
}