tersify 0.5.0

Universal LLM context compressor — pipe anything, get token-optimized output
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
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
use anyhow::{Context, Result};
use std::path::PathBuf;

const TERSIFY_HOOK_COMMAND: &str = "tersify hook";

const CURSOR_RULE_CONTENT: &str = r#"---
description: Use tersify to compress file content before adding to context — saves 30-78% of tokens
alwaysApply: true
---

# tersify — automatic token compression

Before reading any file into your context, run it through `tersify` first.
This strips comments, blank lines, null JSON fields, and duplicate log lines
without losing any information — saving 30–78% of tokens.

## Usage

```bash
# Compress a single file (replaces comments/blanks, keeps all logic)
tersify src/main.rs

# Compress an entire directory in parallel
tersify src/

# Pipe output from any command
cat large_file.rs | tersify
git diff | tersify

# Signatures only — stub function bodies (saves 50-80%)
tersify --ast src/lib.rs

# Show savings
tersify --verbose src/main.rs
```

## When to use
- ALWAYS run `tersify` before reading source files into context
- Run `tersify src/` when exploring an unfamiliar codebase
- Run `git diff | tersify` before code review to save context space
- Run `tersify --ast` when you only need the API surface, not implementations

## What tersify removes
- Single-line comments (`//`, `#`, `--`)
- Block comments (`/* */`, `""" """`)
- Blank lines and trailing whitespace
- null/empty fields in JSON
- Duplicate log lines (keeps first + count)

tersify is installed at: $(which tersify 2>/dev/null || echo "cargo install tersify")
"#;

const COPILOT_INSTRUCTIONS_CONTENT: &str = r#"## tersify — automatic token compression

Before reading any source file into context, run it through `tersify` first.
tersify strips comments, blank lines, null JSON fields, and duplicate log lines
without losing any information — saving 30–78% of tokens.

### Usage

```bash
tersify src/main.rs          # compress a single file
tersify src/                 # compress entire directory in parallel
cat file.rs | tersify        # pipe any output
git diff | tersify           # compress diffs
tersify --ast src/lib.rs     # signatures only (50–80% savings)
tersify --verbose src/       # show token counts
```

### When to use

- Always run `tersify` before reading source files — every read saves tokens
- Run `tersify src/` when exploring an unfamiliar codebase
- Run `git diff | tersify` before code review
- Run `tersify --ast` when you only need API signatures, not implementations

### What tersify removes

- Single-line comments (`//`, `#`, `--`) and block comments (`/* */`, `""" """`)
- Consecutive blank lines and trailing whitespace
- `null` / empty fields in JSON
- Duplicate log lines (keeps first occurrence + `[×N]` count)
"#;

/// Target IDE for install/uninstall.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Target {
    ClaudeCode,
    Cursor,
    Windsurf,
    Copilot,
}

/// Install tersify hooks for the given target.
pub fn run_with_opts(target: Target) -> Result<()> {
    match target {
        Target::ClaudeCode => install_claude(),
        Target::Cursor => install_cursor(),
        Target::Windsurf => install_windsurf(),
        Target::Copilot => install_copilot(),
    }
}

/// Remove tersify hooks for the given target.
pub fn uninstall_with_opts(target: Target) -> Result<()> {
    match target {
        Target::ClaudeCode => uninstall(),
        Target::Cursor => uninstall_cursor(),
        Target::Windsurf => uninstall_windsurf(),
        Target::Copilot => uninstall_copilot(),
    }
}

/// Detect which AI editors are present on this machine.
fn detect_installed_targets() -> Vec<Target> {
    let home = match std::env::var("HOME") {
        Ok(h) => std::path::PathBuf::from(h),
        Err(_) => return vec![Target::ClaudeCode], // always attempt Claude Code
    };

    let mut targets = Vec::new();

    // Claude Code — ~/.claude/ directory exists or `claude` is on PATH
    if home.join(".claude").exists() || which_exists("claude") {
        targets.push(Target::ClaudeCode);
    } else {
        // Always try Claude Code even if not detected — creates the dir
        targets.push(Target::ClaudeCode);
    }

    // Cursor — ~/.cursor/ directory exists
    if home.join(".cursor").exists() {
        targets.push(Target::Cursor);
    }

    // Windsurf — ~/.windsurf/ directory exists
    if home.join(".windsurf").exists() {
        targets.push(Target::Windsurf);
    }

    targets
}

fn which_exists(cmd: &str) -> bool {
    std::process::Command::new("which")
        .arg(cmd)
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
}

/// Install tersify hooks into all detected AI editors.
pub fn run_all() -> Result<()> {
    let targets = detect_installed_targets();

    if targets.is_empty() {
        println!("No supported AI editors detected. Run one of:");
        println!("  tersify install            # Claude Code");
        println!("  tersify install --cursor   # Cursor");
        println!("  tersify install --windsurf # Windsurf");
        return Ok(());
    }

    println!("Detected editors: {}", format_targets(&targets));
    println!();

    for target in targets {
        run_with_opts(target)?;
    }

    println!();
    println!("✓ All done! Run `tersify stats` to track your token savings.");
    Ok(())
}

/// Uninstall tersify hooks from all detected AI editors.
pub fn uninstall_all() -> Result<()> {
    let targets = detect_installed_targets();
    for target in targets {
        let _ = uninstall_with_opts(target); // best-effort
    }
    Ok(())
}

fn format_targets(targets: &[Target]) -> String {
    targets
        .iter()
        .map(|t| match t {
            Target::ClaudeCode => "Claude Code",
            Target::Cursor => "Cursor",
            Target::Windsurf => "Windsurf",
            Target::Copilot => "GitHub Copilot",
        })
        .collect::<Vec<_>>()
        .join(", ")
}

// ── Claude Code ──────────────────────────────────────────────────────────────

fn install_claude() -> Result<()> {
    let settings_path = claude_settings_path()?;

    // Remove the legacy hooks.json written by older tersify versions
    cleanup_legacy_hooks_json();

    // Load existing settings.json or start fresh
    let mut settings: serde_json::Value = if settings_path.exists() {
        let content = std::fs::read_to_string(&settings_path)
            .with_context(|| format!("failed to read {}", settings_path.display()))?;
        serde_json::from_str(&content).unwrap_or(serde_json::json!({}))
    } else {
        serde_json::json!({})
    };

    if hook_is_installed(&settings) {
        println!(
            "✓ tersify hook already installed in {}",
            settings_path.display()
        );
        return Ok(());
    }

    // Ensure hooks → PostToolUse and PreToolUse arrays exist, then append our entries
    {
        let obj = settings
            .as_object_mut()
            .context("settings.json root is not an object")?;
        let hooks = obj
            .entry("hooks")
            .or_insert_with(|| serde_json::json!({}))
            .as_object_mut()
            .context("settings.json hooks is not an object")?;

        // PostToolUse: Read (compress file content after read)
        let post = hooks
            .entry("PostToolUse")
            .or_insert_with(|| serde_json::json!([]));
        if let Some(arr) = post.as_array_mut() {
            arr.push(serde_json::json!({
                "matcher": "Read",
                "hooks": [{"type": "command", "command": TERSIFY_HOOK_COMMAND}]
            }));
            // PostToolUse: Bash (compress bash command output)
            arr.push(serde_json::json!({
                "matcher": "Bash",
                "hooks": [{"type": "command", "command": TERSIFY_HOOK_COMMAND}]
            }));
        }

        // PreToolUse: Write/Edit (inject compressed current file as context before editing)
        let pre = hooks
            .entry("PreToolUse")
            .or_insert_with(|| serde_json::json!([]));
        if let Some(arr) = pre.as_array_mut() {
            arr.push(serde_json::json!({
                "matcher": "Write",
                "hooks": [{"type": "command", "command": TERSIFY_HOOK_COMMAND}]
            }));
            arr.push(serde_json::json!({
                "matcher": "Edit",
                "hooks": [{"type": "command", "command": TERSIFY_HOOK_COMMAND}]
            }));
        }
    }

    if let Some(parent) = settings_path.parent() {
        std::fs::create_dir_all(parent)
            .with_context(|| format!("failed to create {}", parent.display()))?;
    }

    std::fs::write(
        &settings_path,
        serde_json::to_string_pretty(&settings).context("failed to serialise settings.json")?
            + "\n",
    )
    .with_context(|| format!("failed to write {}", settings_path.display()))?;

    println!(
        "✓ Claude Code — automatic hook installed ({})",
        settings_path.display()
    );
    println!("  Every file Claude reads is now silently compressed.");
    println!("  Nothing to do — it just works. Track savings: tersify stats");
    Ok(())
}

pub fn uninstall() -> Result<()> {
    let settings_path = claude_settings_path()?;

    cleanup_legacy_hooks_json();

    if !settings_path.exists() {
        println!("Nothing to uninstall — ~/.claude/settings.json not found.");
        return Ok(());
    }

    let content = std::fs::read_to_string(&settings_path)
        .with_context(|| format!("failed to read {}", settings_path.display()))?;
    let mut settings: serde_json::Value =
        serde_json::from_str(&content).unwrap_or(serde_json::json!({}));

    if !hook_is_installed(&settings) {
        println!("tersify hook not found in settings.json.");
        return Ok(());
    }

    // Remove all tersify PostToolUse and PreToolUse entries
    for event in &["PostToolUse", "PreToolUse"] {
        let ptr = format!("/hooks/{event}");
        if let Some(arr) = settings.pointer_mut(&ptr).and_then(|v| v.as_array_mut()) {
            arr.retain(|entry| !entry_is_tersify(entry));
        }
    }

    std::fs::write(
        &settings_path,
        serde_json::to_string_pretty(&settings).context("failed to serialise settings.json")?
            + "\n",
    )
    .with_context(|| format!("failed to write {}", settings_path.display()))?;

    println!("✓ Removed tersify hook from {}", settings_path.display());
    Ok(())
}

fn hook_is_installed(settings: &serde_json::Value) -> bool {
    settings
        .pointer("/hooks/PostToolUse")
        .and_then(|v| v.as_array())
        .map(|arr| arr.iter().any(entry_is_tersify))
        .unwrap_or(false)
}

fn entry_is_tersify(entry: &serde_json::Value) -> bool {
    entry
        .get("hooks")
        .and_then(|h| h.as_array())
        .map(|hooks| {
            hooks.iter().any(|h| {
                h.get("command")
                    .and_then(|c| c.as_str())
                    .map(|c| c.contains(TERSIFY_HOOK_COMMAND))
                    .unwrap_or(false)
            })
        })
        .unwrap_or(false)
}

/// Remove the legacy `~/.claude/hooks.json` written by older tersify versions.
fn cleanup_legacy_hooks_json() {
    if let Ok(home) = std::env::var("HOME") {
        let path = PathBuf::from(home).join(".claude").join("hooks.json");
        if path.exists() && std::fs::remove_file(&path).is_ok() {
            println!("  Removed legacy ~/.claude/hooks.json");
        }
    }
}

fn claude_settings_path() -> Result<PathBuf> {
    let home = std::env::var("HOME").context("$HOME not set")?;
    Ok(PathBuf::from(home).join(".claude").join("settings.json"))
}

// ── Cursor IDE ───────────────────────────────────────────────────────────────

fn install_cursor() -> Result<()> {
    let rule_path = cursor_rule_path()?;

    if rule_path.exists() {
        println!(
            "✓ Cursor — rule already installed at {}",
            rule_path.display()
        );
        return Ok(());
    }

    // Create the rules directory if it doesn't exist
    if let Some(parent) = rule_path.parent() {
        std::fs::create_dir_all(parent)
            .with_context(|| format!("failed to create {}", parent.display()))?;
    }

    std::fs::write(&rule_path, CURSOR_RULE_CONTENT)
        .with_context(|| format!("failed to write {}", rule_path.display()))?;

    println!("✓ Cursor — AI rule installed ({})", rule_path.display());
    println!("  Cursor's AI will now always use tersify before reading files.");
    println!("  Note: Cursor uses AI-guided rules (not automatic hooks like Claude Code).");
    println!("  The AI knows to run tersify — it happens transparently.");
    Ok(())
}

fn uninstall_cursor() -> Result<()> {
    let rule_path = cursor_rule_path()?;

    if !rule_path.exists() {
        println!("Nothing to uninstall — Cursor rule not found.");
        return Ok(());
    }

    std::fs::remove_file(&rule_path)
        .with_context(|| format!("failed to remove {}", rule_path.display()))?;

    println!("✓ Removed tersify Cursor rule ({})", rule_path.display());
    Ok(())
}

fn cursor_rule_path() -> Result<PathBuf> {
    let home = std::env::var("HOME").context("$HOME not set")?;
    Ok(PathBuf::from(home)
        .join(".cursor")
        .join("rules")
        .join("tersify.mdc"))
}

// ── Windsurf IDE ──────────────────────────────────────────────────────────────

const WINDSURF_RULE_CONTENT: &str = r#"---
trigger: always_on
---

# tersify — automatic token compression

Before reading any file into your context, run it through `tersify` first.
This strips comments, blank lines, null JSON fields, and duplicate log lines
without losing any information — saving 30–78% of tokens.

## Usage

```bash
tersify src/main.rs          # compress a single file
tersify src/                 # compress entire directory in parallel
cat large_file.rs | tersify  # pipe any command output
git diff | tersify           # compress diffs before review
tersify --ast src/lib.rs     # signatures only (50-80% savings)
tersify --verbose src/       # show token counts
```

## Always do this
- Run `tersify` before reading source files — every read saves tokens
- Run `tersify src/` when exploring a codebase
- Run `tersify --ast` when you only need function signatures

## What tersify removes
- Comments (single-line and block) in all supported languages
- Blank lines and trailing whitespace
- null/empty fields in JSON
- Duplicate log lines (keeps unique lines + count)

tersify installed: $(which tersify 2>/dev/null || echo "cargo install tersify")
"#;

fn install_windsurf() -> Result<()> {
    let rule_path = windsurf_rule_path()?;

    if rule_path.exists() {
        println!(
            "✓ Windsurf — rule already installed at {}",
            rule_path.display()
        );
        return Ok(());
    }

    if let Some(parent) = rule_path.parent() {
        std::fs::create_dir_all(parent)
            .with_context(|| format!("failed to create {}", parent.display()))?;
    }

    std::fs::write(&rule_path, WINDSURF_RULE_CONTENT)
        .with_context(|| format!("failed to write {}", rule_path.display()))?;

    println!("✓ Windsurf — AI rule installed ({})", rule_path.display());
    println!("  Windsurf's AI will now always use tersify before reading files.");
    println!("  Note: Windsurf uses AI-guided rules (not automatic hooks like Claude Code).");
    println!("  The AI knows to run tersify — it happens transparently.");
    Ok(())
}

fn uninstall_windsurf() -> Result<()> {
    let rule_path = windsurf_rule_path()?;

    if !rule_path.exists() {
        println!("Nothing to uninstall — Windsurf rule not found.");
        return Ok(());
    }

    std::fs::remove_file(&rule_path)
        .with_context(|| format!("failed to remove {}", rule_path.display()))?;

    println!("✓ Removed tersify Windsurf rule ({})", rule_path.display());
    Ok(())
}

fn windsurf_rule_path() -> Result<PathBuf> {
    let home = std::env::var("HOME").context("$HOME not set")?;
    Ok(PathBuf::from(home)
        .join(".windsurf")
        .join("rules")
        .join("tersify.md"))
}

// ── GitHub Copilot ────────────────────────────────────────────────────────────

/// Install tersify instructions into `.github/copilot-instructions.md` in the
/// current working directory.
///
/// If the file already exists, the tersify section is appended (idempotent).
fn install_copilot() -> Result<()> {
    let path = copilot_path()?;

    // Check if our section is already there
    if path.exists() {
        let existing = std::fs::read_to_string(&path)
            .with_context(|| format!("failed to read {}", path.display()))?;
        if existing.contains("tersify") {
            println!("✓ GitHub Copilot — tersify already in {}", path.display());
            return Ok(());
        }
        // Append to existing file
        let mut content = existing;
        content.push_str("\n---\n\n");
        content.push_str(COPILOT_INSTRUCTIONS_CONTENT);
        std::fs::write(&path, content)
            .with_context(|| format!("failed to write {}", path.display()))?;
    } else {
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)
                .with_context(|| format!("failed to create {}", parent.display()))?;
        }
        std::fs::write(&path, COPILOT_INSTRUCTIONS_CONTENT)
            .with_context(|| format!("failed to write {}", path.display()))?;
    }

    println!(
        "✓ GitHub Copilot — instructions installed ({})",
        path.display()
    );
    println!("  Copilot will now suggest running tersify before reading files.");
    Ok(())
}

fn uninstall_copilot() -> Result<()> {
    let path = copilot_path()?;

    if !path.exists() {
        println!("Nothing to uninstall — {} not found.", path.display());
        return Ok(());
    }

    let content = std::fs::read_to_string(&path)
        .with_context(|| format!("failed to read {}", path.display()))?;

    if !content.contains("tersify") {
        println!("tersify section not found in {}.", path.display());
        return Ok(());
    }

    // Remove the tersify section (everything after the last `---\n\n` before it,
    // or the whole file if tersify is the only content).
    let stripped = remove_tersify_section(&content);
    if stripped.trim().is_empty() {
        std::fs::remove_file(&path)
            .with_context(|| format!("failed to remove {}", path.display()))?;
        println!("✓ Removed {} (was only tersify content)", path.display());
    } else {
        std::fs::write(&path, stripped)
            .with_context(|| format!("failed to write {}", path.display()))?;
        println!("✓ Removed tersify section from {}", path.display());
    }
    Ok(())
}

/// Remove the tersify block from copilot-instructions content.
fn remove_tersify_section(content: &str) -> String {
    // If the file starts with the tersify section (no prior content), return empty.
    if content.trim_start().starts_with("## tersify") {
        return String::new();
    }
    // Otherwise, remove `\n---\n\n## tersify ...` to end of file.
    if let Some(pos) = content.find("\n---\n\n## tersify") {
        return content[..pos].to_string();
    }
    // Fallback: remove any line that mentions tersify and trailing blank lines.
    content
        .lines()
        .filter(|l| !l.contains("tersify"))
        .collect::<Vec<_>>()
        .join("\n")
}

fn copilot_path() -> Result<std::path::PathBuf> {
    let cwd = std::env::current_dir().context("failed to get current directory")?;
    Ok(cwd.join(".github").join("copilot-instructions.md"))
}

// ── Tests ─────────────────────────────────────────────────────────────────────

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

    #[test]
    #[cfg(unix)]
    fn windsurf_rule_path_structure() {
        let path = windsurf_rule_path().unwrap();
        let s = path.to_string_lossy();
        assert!(s.contains(".windsurf"));
        assert!(s.contains("rules"));
        assert!(s.ends_with("tersify.md"));
    }

    #[test]
    #[cfg(unix)]
    fn cursor_rule_path_structure() {
        let path = cursor_rule_path().unwrap();
        let s = path.to_string_lossy();
        assert!(s.contains(".cursor"));
        assert!(s.contains("rules"));
        assert!(s.ends_with("tersify.mdc"));
    }

    #[test]
    #[cfg(unix)]
    fn claude_settings_path_structure() {
        let path = claude_settings_path().unwrap();
        let s = path.to_string_lossy();
        assert!(s.contains(".claude"));
        assert!(s.ends_with("settings.json"));
    }

    #[test]
    fn windsurf_rule_content_has_trigger() {
        assert!(WINDSURF_RULE_CONTENT.contains("trigger: always_on"));
        assert!(WINDSURF_RULE_CONTENT.contains("tersify"));
    }

    #[test]
    fn cursor_rule_content_has_always_apply() {
        assert!(CURSOR_RULE_CONTENT.contains("alwaysApply: true"));
        assert!(CURSOR_RULE_CONTENT.contains("tersify"));
    }

    #[test]
    fn resolve_target_flags() {
        // This replicates main.rs resolve_target logic
        assert_eq!(Target::ClaudeCode, Target::ClaudeCode);
        assert_ne!(Target::Cursor, Target::Windsurf);
    }
}