bctx-weave 0.1.6

bctx-weave — FilterMesh lens pipeline, CLI interception, domain compression
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
use forge::signal::compactor;
use once_cell::sync::Lazy;
use regex::Regex;

// ── Noise-line patterns ───────────────────────────────────────────────────────

static GIT_HINT_RE: Lazy<Regex> = Lazy::new(|| {
    Regex::new(r#"(?m)^\s*(\(use "git|hint:|nothing to commit|no changes added)"#).unwrap()
});
static GIT_OBJECT_COUNT_RE: Lazy<Regex> = Lazy::new(|| {
    Regex::new(r"(?m)^(Counting|Compressing|remote: Counting|remote: Compressing|Receiving|Resolving|Writing) objects:.*\n?").unwrap()
});
static GIT_DELTA_RE: Lazy<Regex> =
    Lazy::new(|| Regex::new(r"(?m)^(remote: )?delta compression.*\n?").unwrap());
static GIT_INDEX_RE: Lazy<Regex> = Lazy::new(|| {
    // diff index lines like: "index abc123..def456 100644"
    Regex::new(r"(?m)^index [0-9a-f]+\.\.[0-9a-f]+ \d+\n?").unwrap()
});
static GIT_SIMILARITY_RE: Lazy<Regex> = Lazy::new(|| {
    Regex::new(r"(?m)^similarity index \d+%\n?(rename from .*\nrename to .*\n?)?").unwrap()
});
static GIT_COMMIT_SIGNING_RE: Lazy<Regex> = Lazy::new(|| {
    Regex::new(r"(?m)^( +gpg:|-----BEGIN PGP|-----END PGP|gpg: Signature).*\n?").unwrap()
});
static GIT_BLAME_HEADER_RE: Lazy<Regex> =
    Lazy::new(|| Regex::new(r"(?m)^[0-9a-f]{40} \(").unwrap());

// ── git log ───────────────────────────────────────────────────────────────────

/// Compress `git log --oneline` output: keep first + last few commits, summarise middle.
pub fn compress_log(raw: &str, max_commits: usize) -> String {
    let cleaned = compactor::normalise(raw);
    let lines: Vec<&str> = cleaned.lines().filter(|l| !l.trim().is_empty()).collect();

    if lines.len() <= max_commits {
        return cleaned;
    }

    let head = max_commits / 2;
    let tail = max_commits - head;
    let skipped = lines.len() - head - tail;

    format!(
        "{}\n... [{skipped} commits omitted] ...\n{}",
        lines[..head].join("\n"),
        lines[lines.len() - tail..].join("\n"),
    )
}

/// Compress verbose `git log` (multi-line per commit): keep hash + subject only.
pub fn compress_log_verbose(raw: &str) -> String {
    let cleaned = compactor::normalise(raw);
    let noise_prefixes = ["Author:", "Date:", "Merge:", "    "];
    let mut out = Vec::new();
    for line in cleaned.lines() {
        let t = line.trim();
        if t.is_empty() {
            continue;
        }
        if noise_prefixes.iter().any(|p| line.starts_with(p)) {
            continue;
        }
        // Commit line: "commit <hash>"  → shorten hash
        if let Some(rest) = line.strip_prefix("commit ") {
            out.push(format!("commit {}", &rest[..8.min(rest.len())]));
        } else {
            out.push(line.to_string());
        }
    }
    out.join("\n")
}

// ── git diff ──────────────────────────────────────────────────────────────────

/// Compress full `git diff` output: strip noise lines, keep hunks.
pub fn compress_diff(raw: &str) -> String {
    let cleaned = compactor::normalise(raw);
    let s1 = GIT_INDEX_RE.replace_all(&cleaned, "");
    let s2 = GIT_SIMILARITY_RE.replace_all(&s1, "");
    // Count changed files; if > 8, show first 8 + summary
    let file_headers: Vec<&str> = s2.lines().filter(|l| l.starts_with("diff --git")).collect();
    if file_headers.len() > 8 {
        let truncated = truncate_diff_to_n_files(&s2, 8);
        return format!(
            "{}\n... [{} more files not shown] ...",
            truncated,
            file_headers.len() - 8
        );
    }
    s2.into_owned()
}

/// Compress `git diff --stat` output.
pub fn compress_diff_stat(raw: &str) -> String {
    let cleaned = compactor::normalise(raw);
    let lines: Vec<&str> = cleaned.lines().filter(|l| !l.trim().is_empty()).collect();
    if let Some(last) = lines.last() {
        if lines.len() > 6 {
            let files_shown = 5.min(lines.len() - 1);
            let shown = lines[..files_shown].to_vec();
            return format!(
                "{}\n... [{} more files] ...\n{}",
                shown.join("\n"),
                lines.len() - 1 - files_shown,
                last
            );
        }
    }
    cleaned
}

fn truncate_diff_to_n_files(diff: &str, n: usize) -> String {
    let mut count = 0;
    let mut out = String::new();
    for line in diff.lines() {
        if line.starts_with("diff --git") {
            count += 1;
            if count > n {
                break;
            }
        }
        out.push_str(line);
        out.push('\n');
    }
    out
}

// ── git status ────────────────────────────────────────────────────────────────

/// Compress `git status` output by removing redundant hints and usage lines.
pub fn compress_status(raw: &str) -> String {
    let cleaned = compactor::normalise(raw);
    // Strip hint lines
    let stripped = GIT_HINT_RE.replace_all(&cleaned, "");
    // Collapse long untracked-file lists (> 10 entries → "and N more")
    let mut out: Vec<&str> = Vec::new();
    let mut untracked_count = 0usize;
    let mut in_untracked = false;
    let max_untracked = 8;

    for line in stripped.lines() {
        if line.contains("Untracked files:") {
            in_untracked = true;
        }
        if line.contains("Changes to be committed:") || line.contains("Changes not staged") {
            in_untracked = false;
        }
        if in_untracked && line.starts_with('\t') {
            untracked_count += 1;
            if untracked_count <= max_untracked {
                out.push(line);
            } else if untracked_count == max_untracked + 1 {
                out.push("  ... and more untracked files (run git status for full list)");
            }
        } else {
            out.push(line);
        }
    }
    compactor::collapse_blanks(&out.join("\n"))
}

// ── git commit ────────────────────────────────────────────────────────────────

/// Compress `git commit` output: strip signing, hooks noise, keep summary.
pub fn compress_commit(raw: &str) -> String {
    let cleaned = compactor::normalise(raw);
    let s1 = GIT_COMMIT_SIGNING_RE.replace_all(&cleaned, "");
    // Strip pre/post-commit hook progress lines (often "[hook] running…" type lines)
    let out: Vec<&str> = s1
        .lines()
        .filter(|l| {
            let t = l.trim();
            !t.starts_with("running ") && !t.contains("pre-commit") && !t.contains("post-commit")
        })
        .collect();
    compactor::collapse_blanks(&out.join("\n"))
}

// ── git fetch / pull ──────────────────────────────────────────────────────────

/// Compress `git fetch` / `git pull` output: strip object-count progress.
pub fn compress_fetch(raw: &str) -> String {
    let cleaned = compactor::normalise(raw);
    let s1 = GIT_OBJECT_COUNT_RE.replace_all(&cleaned, "");
    let s2 = GIT_DELTA_RE.replace_all(&s1, "");
    // Strip "remote:" lines that are just whitespace padding
    let out: Vec<&str> = s2.lines().filter(|l| l.trim() != "remote:").collect();
    compactor::collapse_blanks(&out.join("\n"))
}

// ── git blame ───────────────────────────────────────────────────────────────���─

/// Compress `git blame`: shorten 40-char SHAs to 8-char, deduplicate repeated author+date.
pub fn compress_blame(raw: &str) -> String {
    let cleaned = compactor::normalise(raw);
    if !GIT_BLAME_HEADER_RE.is_match(&cleaned) {
        return cleaned;
    }
    // Shorten SHA from 40 to 8 chars
    let short_sha_re = Regex::new(r"^[0-9a-f]{40}").unwrap();
    let lines: Vec<String> = cleaned
        .lines()
        .map(|l| {
            if short_sha_re.is_match(l) {
                format!("{}{}", &l[..8], &l[40..])
            } else {
                l.to_string()
            }
        })
        .collect();
    lines.join("\n")
}

// ── git stash / branch / remote ──────────────────────────────────────────────

/// Compact `git stash list` output: truncate to 20 entries.
pub fn compress_stash_list(raw: &str) -> String {
    let cleaned = compactor::normalise(raw);
    let lines: Vec<&str> = cleaned.lines().filter(|l| !l.trim().is_empty()).collect();
    if lines.len() <= 20 {
        return lines.join("\n");
    }
    format!(
        "{}\n... [{} more stash entries]",
        lines[..20].join("\n"),
        lines.len() - 20
    )
}

static GIT_BRANCH_TRACKING_RE: Lazy<Regex> =
    Lazy::new(|| Regex::new(r" \[(?:ahead \d+(?:, )?)?(?:behind \d+)?\]").unwrap());

/// Compact `git branch -v[v]`: strip tracking noise, keep name + hash + subject.
/// Truncate at 40 branches.
pub fn compress_branch(raw: &str) -> String {
    let cleaned = compactor::normalise(raw);
    let s = GIT_BRANCH_TRACKING_RE.replace_all(&cleaned, "");
    let lines: Vec<&str> = s.lines().filter(|l| !l.trim().is_empty()).collect();
    if lines.len() <= 40 {
        return lines.join("\n");
    }
    format!(
        "{}\n... [{} more branches]",
        lines[..40].join("\n"),
        lines.len() - 40
    )
}

/// Compact `git tag -l`: truncate at 30 tags.
pub fn compress_tag(raw: &str) -> String {
    let cleaned = compactor::normalise(raw);
    let lines: Vec<&str> = cleaned.lines().filter(|l| !l.trim().is_empty()).collect();
    if lines.len() <= 30 {
        return lines.join("\n");
    }
    format!(
        "{}\n... [{} more tags]",
        lines[..30].join("\n"),
        lines.len() - 30
    )
}

/// Compact `git remote -v`: deduplicate fetch/push pairs (show fetch URL only).
pub fn compress_remote(raw: &str) -> String {
    let cleaned = compactor::normalise(raw);
    // Remove " (push)" duplicate lines — keep "(fetch)" lines and plain lines
    let lines: Vec<&str> = cleaned.lines().filter(|l| !l.ends_with("(push)")).collect();
    lines.join("\n")
}

/// Compact `git rebase` output: strip "Rebasing (N/M)" progress, keep result.
pub fn compress_rebase(raw: &str) -> String {
    let cleaned = compactor::normalise(raw);
    let rebase_progress_re = Regex::new(r"(?m)^Rebasing \(\d+/\d+\)\n?").unwrap();
    let s = rebase_progress_re.replace_all(&cleaned, "");
    compactor::collapse_blanks(&s)
}

/// Compact `git cherry-pick` output: keep conflict info, strip applied-cleanly noise.
pub fn compress_cherry_pick(raw: &str) -> String {
    let cleaned = compactor::normalise(raw);
    // If no conflicts, keep only the first line (commit hash + subject)
    if !cleaned.contains("CONFLICT") && !cleaned.contains("conflict") {
        return cleaned.lines().next().unwrap_or("").to_string();
    }
    cleaned
}

/// Compact `git show`: treat as diff but also keep commit header (first ~5 lines).
pub fn compress_show(raw: &str) -> String {
    let cleaned = compactor::normalise(raw);
    let s1 = GIT_INDEX_RE.replace_all(&cleaned, "");
    let s2 = GIT_SIMILARITY_RE.replace_all(&s1, "");
    compactor::collapse_blanks(&s2)
}

/// Compact `git worktree list`: normalise only (output is already compact).
pub fn compress_worktree(raw: &str) -> String {
    compactor::normalise(raw)
}

/// Compact `git gc` output: strip object counting/compressing noise.
pub fn compress_gc(raw: &str) -> String {
    let cleaned = compactor::normalise(raw);
    let s = GIT_OBJECT_COUNT_RE.replace_all(&cleaned, "");
    compactor::collapse_blanks(&s)
}

/// Compact `git submodule` output.
pub fn compress_submodule(raw: &str) -> String {
    let cleaned = compactor::normalise(raw);
    // Strip "Submodule path 'X': checked out 'sha'" noise on update
    let lines: Vec<&str> = cleaned
        .lines()
        .filter(|l| {
            let t = l.trim();
            !t.is_empty()
                && (!t.starts_with("Cloning into") || t.len() <= 60)
                && !t.starts_with("remote: Counting")
                && !t.starts_with("remote: Compressing")
                && !t.starts_with("Receiving objects:")
                && !t.starts_with("Resolving deltas:")
        })
        .collect();
    lines.join("\n")
}

/// Compact `git bisect` output: keep only actionable lines.
pub fn compress_bisect(raw: &str) -> String {
    let cleaned = compactor::normalise(raw);
    // Keep: "Bisecting: N revisions left", "is the first bad commit", error lines
    let out: Vec<&str> = cleaned
        .lines()
        .filter(|l| {
            l.starts_with("Bisecting:")
                || l.contains("first bad commit")
                || l.starts_with("commit ")
                || l.starts_with("[")
                || l.starts_with("error")
                || l.starts_with("fatal")
        })
        .collect();
    if out.is_empty() {
        cleaned
    } else {
        out.join("\n")
    }
}

// ── top-level dispatcher ─────────────────────────────────────────────────────

/// Route git output to the right compressor by sub-command.
pub fn compress_git(subcmd: &str, raw: &str, exit_code: i32) -> String {
    if exit_code != 0 {
        return compactor::normalise(raw);
    }
    let sub = subcmd.trim();

    if sub.starts_with("log") {
        // Verbose log has "commit <sha>" lines
        if raw
            .lines()
            .any(|l| l.starts_with("commit ") && l.len() == 47)
        {
            return compress_log_verbose(raw);
        }
        return compress_log(raw, 12);
    }
    if sub.starts_with("diff") {
        if sub.contains("--stat") {
            return compress_diff_stat(raw);
        }
        return compress_diff(raw);
    }
    if sub.starts_with("status") {
        return compress_status(raw);
    }
    if sub.starts_with("commit") {
        return compress_commit(raw);
    }
    if sub.starts_with("fetch") || sub.starts_with("pull") {
        return compress_fetch(raw);
    }
    if sub.starts_with("blame") {
        return compress_blame(raw);
    }
    if sub.starts_with("stash") {
        return compress_stash_list(raw);
    }
    if sub.starts_with("branch") {
        return compress_branch(raw);
    }
    if sub.starts_with("tag") {
        return compress_tag(raw);
    }
    if sub.starts_with("remote") {
        return compress_remote(raw);
    }
    if sub.starts_with("rebase") {
        return compress_rebase(raw);
    }
    if sub.starts_with("cherry-pick") {
        return compress_cherry_pick(raw);
    }
    if sub.starts_with("show") {
        return compress_show(raw);
    }
    if sub.starts_with("worktree") {
        return compress_worktree(raw);
    }
    if sub.starts_with("bisect") {
        return compress_bisect(raw);
    }
    if sub.starts_with("gc") {
        return compress_gc(raw);
    }
    if sub.starts_with("submodule") {
        return compress_submodule(raw);
    }

    // Generic: normalise + collapse blanks
    let cleaned = compactor::normalise(raw);
    let s = GIT_OBJECT_COUNT_RE.replace_all(&cleaned, "");
    compactor::collapse_blanks(&s)
}

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

    #[test]
    fn log_compression_keeps_head_tail() {
        let log = (0..20)
            .map(|i| format!("abc{i:04} commit message {i}"))
            .collect::<Vec<_>>()
            .join("\n");
        let out = compress_log(&log, 6);
        assert!(out.contains("omitted"), "should summarise middle: {out}");
        assert!(out.lines().count() < 20);
    }

    #[test]
    fn diff_stat_truncates_long_lists() {
        let mut s = String::new();
        for i in 0..20 {
            s.push_str(&format!(" file{i}.rs | 10 ++--\n"));
        }
        s.push_str(" 20 files changed, 100 insertions(+), 50 deletions(-)\n");
        let out = compress_diff_stat(&s);
        assert!(out.contains("more files"));
        assert!(out.contains("20 files changed"));
    }

    #[test]
    fn status_strips_hints() {
        let raw =
            "On branch main\nChanges not staged:\n  (use \"git add\" ...)\n\tmodified: foo.rs\n";
        let out = compress_status(raw);
        assert!(!out.contains("use \"git"), "should strip hints: {out}");
        assert!(out.contains("foo.rs"));
    }

    #[test]
    fn commit_strips_signing() {
        let raw = "[main abc1234] feat: add thing\n gpg: Signature made Mon\n 1 file changed\n";
        let out = compress_commit(raw);
        assert!(!out.contains("gpg:"));
        assert!(out.contains("feat: add thing"));
    }

    #[test]
    fn fetch_strips_object_count() {
        let raw = "remote: Counting objects: 10, done.\nFrom github.com:org/repo\n   abc..def  main -> origin/main\n";
        let out = compress_fetch(raw);
        assert!(!out.contains("Counting objects"));
        assert!(out.contains("main -> origin/main"));
    }

    #[test]
    fn diff_strips_index_lines() {
        let raw = "diff --git a/foo.rs b/foo.rs\nindex abc123..def456 100644\n--- a/foo.rs\n+++ b/foo.rs\n@@ -1,3 +1,4 @@\n+new line\n";
        let out = compress_diff(raw);
        assert!(
            !out.contains("index abc123"),
            "index line should be stripped: {out}"
        );
        assert!(out.contains("+new line"));
    }

    #[test]
    fn diff_truncates_many_files() {
        let mut s = String::new();
        for i in 0..12 {
            s.push_str(&format!("diff --git a/f{i}.rs b/f{i}.rs\n--- a/f{i}.rs\n+++ b/f{i}.rs\n@@ -1 +1 @@\n-old\n+new\n"));
        }
        let out = compress_diff(&s);
        assert!(out.contains("more files not shown"));
    }

    #[test]
    fn stash_list_truncates_at_20() {
        let raw = (0..30)
            .map(|i| format!("stash@{{{i}}}: On main: WIP change {i}"))
            .collect::<Vec<_>>()
            .join("\n");
        let out = compress_stash_list(&raw);
        assert!(out.contains("more stash entries"), "{out}");
    }

    #[test]
    fn tag_list_truncates_at_30() {
        let raw = (0..50)
            .map(|i| format!("v1.{i}.0"))
            .collect::<Vec<_>>()
            .join("\n");
        let out = compress_tag(&raw);
        assert!(out.contains("more tags"), "{out}");
    }

    #[test]
    fn remote_deduplicates_push_lines() {
        let raw = "origin\thttps://github.com/org/repo.git (fetch)\norigin\thttps://github.com/org/repo.git (push)\n";
        let out = compress_remote(raw);
        assert!(!out.contains("(push)"), "{out}");
        assert!(out.contains("(fetch)") || out.contains("origin"), "{out}");
    }

    #[test]
    fn rebase_strips_progress() {
        let raw = "Rebasing (1/10)\nRebasing (2/10)\nRebasing (10/10)\nSuccessfully rebased and updated refs/heads/main.\n";
        let out = compress_rebase(raw);
        assert!(!out.contains("Rebasing (1/10)"), "{out}");
        assert!(out.contains("Successfully rebased"), "{out}");
    }

    #[test]
    fn cherry_pick_clean_keeps_first_line_only() {
        let raw = "[main abc1234] feat: add thing\n Date: Mon Jan 1 12:00:00 2024\n 1 file changed, 5 insertions(+)\n";
        let out = compress_cherry_pick(raw);
        // Should keep only the first summary line
        assert!(out.contains("feat: add thing"), "{out}");
        assert!(!out.contains("Date:"), "{out}");
    }
}