crosslink 0.8.0

A synced issue tracker CLI for multi-agent AI development
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
use anyhow::{Context, Result};
use std::fs;
use std::path::Path;

use crate::commands::init;
use crate::ContextCommands;

/// Language detection: maps manifest files to (language name, rule filename).
const LANGUAGE_MANIFESTS: &[(&str, &str, &str)] = &[
    ("Cargo.toml", "Rust", "rust.md"),
    ("package.json", "JavaScript", "javascript.md"),
    ("tsconfig.json", "TypeScript", "typescript.md"),
    ("pyproject.toml", "Python", "python.md"),
    ("requirements.txt", "Python", "python.md"),
    ("go.mod", "Go", "go.md"),
    ("pom.xml", "Java", "java.md"),
    ("build.gradle", "Java", "java.md"),
    ("Gemfile", "Ruby", "ruby.md"),
    ("composer.json", "PHP", "php.md"),
    ("Package.swift", "Swift", "swift.md"),
    ("CMakeLists.txt", "C/C++", "cpp.md"),
    ("Makefile", "C/C++", "c.md"),
    ("mix.exs", "Elixir", "elixir.md"),
    (".shellcheckrc", "Shell", "shell.md"),
];

/// Expected hook files that should exist in .claude/hooks/.
const EXPECTED_HOOKS: &[&str] = &[
    "prompt-guard.py",
    "post-edit-check.py",
    "session-start.py",
    "pre-web-check.py",
    "work-check.py",
    "crosslink_config.py",
];

/// Expected command files that should exist in .claude/commands/.
const EXPECTED_COMMANDS: &[&str] = &[
    "workflow.md",
    "feature.md",
    "featree.md",
    "kickoff.md",
    "check.md",
    "commit.md",
    "preflight.md",
    "review.md",
    "audit.md",
];

/// Expected rule files in .crosslink/rules/.
const EXPECTED_RULES: &[&str] = &[
    "global.md",
    "project.md",
    "tracking-strict.md",
    "tracking-normal.md",
    "tracking-relaxed.md",
];

pub fn run(command: ContextCommands, crosslink_dir: &Path) -> Result<()> {
    match command {
        ContextCommands::Measure { verbose } => measure(crosslink_dir, verbose),
        ContextCommands::Check => {
            let claude_dir = crosslink_dir
                .parent()
                .context("Cannot determine project root")?
                .join(".claude");
            check(crosslink_dir, &claude_dir);
            Ok(())
        }
    }
}

// ---------------------------------------------------------------------------
// measure — report context injection sizes
// ---------------------------------------------------------------------------

fn measure(crosslink_dir: &Path, verbose: bool) -> Result<()> {
    let project_root = crosslink_dir
        .parent()
        .context("Cannot determine project root")?;

    println!("Context injection measurement");
    println!("{}", "=".repeat(60));

    // 1. Rule files
    let rules_dir = crosslink_dir.join("rules");
    let mut total_rules: usize = 0;
    let mut active_rules: usize = 0;
    let mut dormant_rules: usize = 0;

    // Detect active languages
    let active_langs = detect_active_languages(project_root);

    let rules_local_dir = crosslink_dir.join("rules.local");

    println!("\n## Rule files (.crosslink/rules/)");
    println!("{:<35} {:>8} {:>8}  STATUS", "FILE", "BYTES", "~TOKENS");
    println!("{}", "-".repeat(65));

    // Collect overridden filenames from rules.local/
    let local_overrides: std::collections::HashSet<String> = if rules_local_dir.is_dir() {
        fs::read_dir(&rules_local_dir)
            .ok()
            .into_iter()
            .flatten()
            .filter_map(std::result::Result::ok)
            .map(|e| e.file_name().to_string_lossy().to_string())
            .collect()
    } else {
        std::collections::HashSet::new()
    };

    if rules_dir.is_dir() {
        let mut entries: Vec<_> = fs::read_dir(&rules_dir)
            .context("Failed to read rules directory")?
            .filter_map(std::result::Result::ok)
            .filter(|e| {
                e.path()
                    .extension()
                    .is_some_and(|ext| ext == "md" || ext == "txt")
            })
            .collect();
        entries.sort_by_key(std::fs::DirEntry::file_name);

        for entry in &entries {
            let path = entry.path();
            let filename = entry.file_name().to_string_lossy().to_string();

            // If overridden by rules.local/, show the local version's size
            let (size, suffix) = if local_overrides.contains(&filename) {
                let local_path = rules_local_dir.join(&filename);
                let s = fs::metadata(&local_path).map_or(0, |m| m.len() as usize);
                (s, " (local)")
            } else {
                let s = fs::metadata(&path).map_or(0, |m| m.len() as usize);
                (s, "")
            };
            let tokens = size / 4;
            total_rules += size;

            let is_active = is_rule_active(&filename, &active_langs);
            let status = if is_active {
                active_rules += size;
                "active"
            } else {
                dormant_rules += size;
                "dormant"
            };

            println!("{filename:<35} {size:>8} {tokens:>8}  {status}{suffix}");
        }
    }

    // Show additive rules from rules.local/ (files not present in rules/)
    if rules_local_dir.is_dir() {
        let base_files: std::collections::HashSet<String> = if rules_dir.is_dir() {
            fs::read_dir(&rules_dir)
                .ok()
                .into_iter()
                .flatten()
                .filter_map(std::result::Result::ok)
                .map(|e| e.file_name().to_string_lossy().to_string())
                .collect()
        } else {
            std::collections::HashSet::new()
        };

        let mut local_entries: Vec<_> = fs::read_dir(&rules_local_dir)
            .ok()
            .into_iter()
            .flatten()
            .filter_map(std::result::Result::ok)
            .filter(|e| {
                let name = e.file_name().to_string_lossy().to_string();
                !base_files.contains(&name)
                    && e.path()
                        .extension()
                        .is_some_and(|ext| ext == "md" || ext == "txt")
            })
            .collect();
        local_entries.sort_by_key(std::fs::DirEntry::file_name);

        for entry in &local_entries {
            let path = entry.path();
            let filename = entry.file_name().to_string_lossy().to_string();
            let size = fs::metadata(&path).map_or(0, |m| m.len() as usize);
            let tokens = size / 4;
            total_rules += size;
            active_rules += size;

            println!("{filename:<35} {size:>8} {tokens:>8}  active (local)");
        }
    }

    println!();
    println!(
        "  Total rules:   {:>8} bytes ({} tokens)",
        total_rules,
        total_rules / 4
    );
    println!(
        "  Active rules:  {:>8} bytes ({} tokens)",
        active_rules,
        active_rules / 4
    );
    println!(
        "  Dormant rules: {:>8} bytes ({} tokens)",
        dormant_rules,
        dormant_rules / 4
    );

    // 2. Active languages
    println!("\n## Detected languages");
    if active_langs.is_empty() {
        println!("  (none detected)");
    } else {
        for lang in &active_langs {
            println!("  - {lang}");
        }
    }

    // 3. CLAUDE.md
    let claude_md = project_root.join("CLAUDE.md");
    let claude_md_size = if claude_md.is_file() {
        fs::metadata(&claude_md).map_or(0, |m| m.len() as usize)
    } else {
        0
    };

    println!("\n## CLAUDE.md");
    if claude_md_size > 0 {
        println!(
            "  {:>8} bytes ({} tokens)",
            claude_md_size,
            claude_md_size / 4
        );
    } else {
        println!("  (not found)");
    }

    // 4. Skill files (.claude/commands/)
    let commands_dir = project_root.join(".claude/commands");
    let mut total_skills: usize = 0;

    println!("\n## Skill files (.claude/commands/)");
    if commands_dir.is_dir() {
        println!("{:<35} {:>8} {:>8}", "FILE", "BYTES", "~TOKENS");
        println!("{}", "-".repeat(55));

        let mut entries: Vec<_> = fs::read_dir(&commands_dir)
            .context("Failed to read commands directory")?
            .filter_map(std::result::Result::ok)
            .filter(|e| e.path().extension().is_some_and(|ext| ext == "md"))
            .collect();
        entries.sort_by_key(std::fs::DirEntry::file_name);

        for entry in &entries {
            let path = entry.path();
            let filename = entry.file_name().to_string_lossy().to_string();
            let size = fs::metadata(&path).map_or(0, |m| m.len() as usize);
            total_skills += size;
            println!("{:<35} {:>8} {:>8}", filename, size, size / 4);
        }
        println!();
        println!(
            "  Total skills: {:>8} bytes ({} tokens)",
            total_skills,
            total_skills / 4
        );
    } else {
        println!("  (not found)");
    }

    // 5. Estimated behavioral guard size (first prompt)
    let tree_est: usize = 2000;
    let deps_est: usize = 1200;
    let wrapper_est: usize = 500;
    let full_guard = tree_est + deps_est + active_rules + wrapper_est;

    println!("\n## Estimated first-prompt injection");
    println!("  Project tree:    ~{tree_est:>6} bytes");
    println!("  Dependencies:    ~{deps_est:>6} bytes");
    println!("  Active rules:     {active_rules:>6} bytes");
    println!("  Wrapper/headers: ~{wrapper_est:>6} bytes");
    println!("  ─────────────────────────");
    println!(
        "  Total:           ~{:>6} bytes (~{} tokens)",
        full_guard,
        full_guard / 4
    );

    // 6. Condensed reminder estimate
    let condensed_est: usize = 500;
    println!("\n## Condensed reminder (subsequent prompts)");
    println!(
        "  Estimated:       ~{:>6} bytes (~{} tokens)",
        condensed_est,
        condensed_est / 4
    );

    // 7. Savings comparison
    println!("\n## Adaptive reminder savings (over 50 prompts)");
    let always_total = full_guard + condensed_est * 49;
    // With adaptive (threshold=5): full guard + ~9 condensed reminders
    let adaptive_reminders = 49 / 5; // roughly 9 reminders
    let adaptive_total = full_guard + condensed_est * adaptive_reminders;
    let saved = always_total.saturating_sub(adaptive_total);
    println!(
        "  Always-inject:   ~{:>8} bytes ({} tokens)",
        always_total,
        always_total / 4
    );
    println!(
        "  Adaptive (t=5):  ~{:>8} bytes ({} tokens)",
        adaptive_total,
        adaptive_total / 4
    );
    println!(
        "  Saved:           ~{:>8} bytes ({} tokens, {:.0}%)",
        saved,
        saved / 4,
        if always_total > 0 {
            saved as f64 / always_total as f64 * 100.0
        } else {
            0.0
        }
    );

    if verbose {
        println!("\n## Hook config");
        let config_path = crosslink_dir.join("hook-config.json");
        if config_path.is_file() {
            let content =
                fs::read_to_string(&config_path).context("Failed to read hook-config.json")?;
            println!("{content}");
        } else {
            println!("  (not found)");
        }
    }

    Ok(())
}

fn detect_active_languages(project_root: &Path) -> Vec<String> {
    let mut found = Vec::new();
    let mut seen = std::collections::HashSet::new();

    // Check project root and immediate subdirs
    let mut check_dirs = vec![project_root.to_path_buf()];
    if let Ok(entries) = fs::read_dir(project_root) {
        for entry in entries.filter_map(std::result::Result::ok) {
            let path = entry.path();
            if path.is_dir() {
                let name = entry.file_name().to_string_lossy().to_string();
                if !name.starts_with('.') {
                    check_dirs.push(path);
                }
            }
        }
    }

    for dir in &check_dirs {
        for &(manifest, lang, _rule_file) in LANGUAGE_MANIFESTS {
            if dir.join(manifest).exists() && seen.insert(lang.to_string()) {
                found.push(lang.to_string());
            }
        }
    }

    // Shell detection: scan for .sh files in root, scripts/, and bin/
    if !seen.contains("Shell") {
        let shell_dirs = [
            project_root.to_path_buf(),
            project_root.join("scripts"),
            project_root.join("bin"),
        ];
        'shell_scan: for dir in &shell_dirs {
            if let Ok(entries) = fs::read_dir(dir) {
                for entry in entries.filter_map(std::result::Result::ok) {
                    let name = entry.file_name().to_string_lossy().to_string();
                    if std::path::Path::new(&name).extension().is_some_and(|ext| {
                        ext.eq_ignore_ascii_case("sh") || ext.eq_ignore_ascii_case("bash")
                    }) {
                        seen.insert("Shell".to_string());
                        found.push("Shell".to_string());
                        break 'shell_scan;
                    }
                }
            }
        }
    }

    found
}

fn is_rule_active(filename: &str, active_langs: &[String]) -> bool {
    // Always-active files
    if matches!(
        filename,
        "global.md"
            | "project.md"
            | "tracking-strict.md"
            | "tracking-normal.md"
            | "tracking-relaxed.md"
            | "sanitize-patterns.txt"
            | "knowledge.md"
            | "web.md"
    ) {
        return true;
    }

    // Check if the rule matches a detected language
    for &(_, lang, rule_file) in LANGUAGE_MANIFESTS {
        if filename == rule_file && active_langs.iter().any(|l| l == lang) {
            return true;
        }
    }

    false
}

// ---------------------------------------------------------------------------
// check — verify crosslink deployment integrity
// ---------------------------------------------------------------------------

fn check(crosslink_dir: &Path, claude_dir: &Path) {
    let mut problems = 0;

    println!("Crosslink deployment check");
    println!("{}", "=".repeat(40));

    // 1. Rule files
    println!("\n## Rule files");
    let rules_dir = crosslink_dir.join("rules");
    for &name in EXPECTED_RULES {
        let path = rules_dir.join(name);
        if path.is_file() {
            println!("  OK  {name}");
        } else {
            println!("  MISSING  {name}");
            problems += 1;
        }
    }

    // Also check language rule files
    for &(rule_name, _content) in init::RULE_FILES {
        let path = rules_dir.join(rule_name);
        if path.is_file() {
            // verbose: could print OK
        } else {
            println!("  MISSING  {rule_name}");
            problems += 1;
        }
    }

    // 2. Hook files
    println!("\n## Hook files");
    let hooks_dir = claude_dir.join("hooks");
    for &name in EXPECTED_HOOKS {
        let path = hooks_dir.join(name);
        if path.is_file() {
            println!("  OK  {name}");
        } else {
            println!("  MISSING  {name}");
            problems += 1;
        }
    }

    // 3. Command files
    println!("\n## Command files");
    let commands_dir = claude_dir.join("commands");
    for &name in EXPECTED_COMMANDS {
        let path = commands_dir.join(name);
        if path.is_file() {
            println!("  OK  {name}");
        } else {
            println!("  MISSING  {name}");
            problems += 1;
        }
    }

    // 4. Hook config
    println!("\n## Configuration");
    let config_path = crosslink_dir.join("hook-config.json");
    if config_path.is_file() {
        match fs::read_to_string(&config_path) {
            Ok(content) => match serde_json::from_str::<serde_json::Value>(&content) {
                Ok(_) => println!("  OK  hook-config.json (valid JSON)"),
                Err(e) => {
                    println!("  INVALID  hook-config.json: {e}");
                    problems += 1;
                }
            },
            Err(e) => {
                println!("  ERROR  hook-config.json: {e}");
                problems += 1;
            }
        }
    } else {
        println!("  MISSING  hook-config.json");
        problems += 1;
    }

    // Summary
    println!();
    if problems == 0 {
        println!("All checks passed.");
    } else {
        println!("{problems} problem(s) found. Run `crosslink init --force` to repair.");
        std::process::exit(1);
    }
}