ctxctl 0.1.3

Pure CLI, zero-MCP, stateless context layer for AI coding agents.
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
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
//! `ctxctl` — pure CLI, zero-MCP, stateless context layer for AI coding agents.
//!
//! Implements the CLI contract in `ctxctl-docs/cli-contract.md` (v0.1):
//!
//! - `outline <file>` — symbol outline plus saved% token stats
//! - `symbol <file> --name <s>` — original source slice of one symbol
//! - `read <file> --lines 100-150,200-210` — raw slices of line ranges
//! - `exec <cmd> [--keep <pat>]` — run a command, compress its output
//!
//! Byte-stable by design: output is a pure function of the inputs and config.
//! No timestamps, no counters, no environment dependence.

mod config;
mod deps;

use clap::{Parser, Subcommand, ValueEnum};
use config::Config;
use ctx_symbol::{ParsedSource, Symbol, SymbolKind};
use serde_json::json;
use std::path::{Path, PathBuf};
use std::process::Command as StdCommand;
use std::process::ExitCode;

#[derive(Parser)]
#[command(
    name = "ctxctl",
    version,
    about = "Pure CLI, zero-MCP, stateless context layer for AI coding agents."
)]
struct Cli {
    /// Explicit config file; highest priority (cli-contract.md §6).
    #[arg(long, value_name = "PATH", global = true)]
    config: Option<PathBuf>,
    /// Output format; `json` is the machine contract.
    #[arg(long, value_enum, default_value_t = Format::Text, global = true)]
    format: Format,
    /// Alias for --format=json.
    #[arg(long, global = true)]
    json: bool,
    /// Disable ANSI colors (accepted for contract compliance; output is
    /// already plain).
    #[arg(long, global = true)]
    no_color: bool,
    /// Suppress saved% metrics.
    #[arg(long, global = true)]
    no_saved: bool,
    #[command(subcommand)]
    command: Command,
}

#[derive(Copy, Clone, PartialEq, Eq, ValueEnum)]
enum Format {
    Text,
    Json,
}

#[derive(Subcommand)]
enum Command {
    /// Print a symbol outline of a source file with token savings.
    Outline {
        /// Target file.
        file: PathBuf,
        /// Omit doc comments.
        #[arg(long)]
        no_doc: bool,
        /// Omit line numbers.
        #[arg(long)]
        no_lines: bool,
    },
    /// Print the original source slice of a single symbol.
    Symbol {
        /// Target file.
        file: PathBuf,
        /// Symbol name (exact).
        #[arg(long)]
        name: String,
        /// Return the signature only, not the body.
        #[arg(long, conflicts_with = "compact")]
        signature: bool,
        /// Return an AST-pruned view: signature + fold marker for the body.
        #[arg(long)]
        compact: bool,
        /// Sub-range within the symbol, 1-based, e.g. 3-10.
        #[arg(long, value_name = "N-M", conflicts_with = "compact")]
        lines: Option<String>,
    },
    /// Read a 1-based line range from the original source (no AST).
    Read {
        /// Target file.
        file: PathBuf,
        /// Line range(s), comma-separated, e.g. 100-150,200-210.
        #[arg(long)]
        lines: String,
    },
    /// Print the import/module dependency graph of a file.
    Deps {
        /// Target file.
        file: PathBuf,
    },
    /// Run a command and print its output compressed by ctx-exec.
    Exec {
        /// Command line to run; shell-word quoting applies, e.g. `"cargo test -- --list"`.
        #[arg(allow_hyphen_values = true)]
        cmd: String,
        /// Extra keep regex (rg syntax), appended to configured patterns.
        #[arg(long = "keep", value_name = "PATTERN", action = clap::ArgAction::Append)]
        keep: Vec<String>,
        /// Override configured head summary lines.
        #[arg(long)]
        head: Option<usize>,
        /// Override configured tail summary lines.
        #[arg(long)]
        tail: Option<usize>,
    },
}

/// An error carrying the exit code required by the CLI contract (§5).
struct ExitError {
    code: u8,
    message: String,
}

impl ExitError {
    fn new(code: u8, message: impl Into<String>) -> Self {
        Self {
            code,
            message: message.into(),
        }
    }
}

impl std::fmt::Display for ExitError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.message)
    }
}

fn main() -> ExitCode {
    let cli = Cli::parse();
    match run(&cli) {
        Ok(code) => code,
        Err(err) => {
            let json_mode = cli.json || cli.format == Format::Json;
            if json_mode {
                println!(
                    "{}",
                    json!({ "error": { "code": err.code, "message": err.message } })
                );
            } else {
                eprintln!("error: {}", err.message);
            }
            ExitCode::from(err.code)
        }
    }
}

fn run(cli: &Cli) -> Result<ExitCode, ExitError> {
    let config = config::load(cli.config.as_deref()).map_err(|e| ExitError::new(1, e))?;
    let format = if cli.json { Format::Json } else { cli.format };
    let show_saved = config.general.show_saved && !cli.no_saved;
    match &cli.command {
        Command::Outline {
            file,
            no_doc,
            no_lines,
        } => run_outline(file, *no_doc, *no_lines, format, show_saved, &config),
        Command::Symbol {
            file,
            name,
            signature,
            compact,
            lines,
        } => run_symbol(
            file,
            name,
            *signature,
            *compact,
            lines.as_deref(),
            format,
            show_saved,
        ),
        Command::Read { file, lines } => run_read(file, lines, format, show_saved),
        Command::Deps { file } => run_deps(file, format, show_saved, &config),
        Command::Exec {
            cmd,
            keep,
            head,
            tail,
        } => run_exec(cmd, keep, *head, *tail, format, show_saved, &config),
    }
}

fn run_outline(
    path: &Path,
    no_doc: bool,
    no_lines: bool,
    format: Format,
    show_saved: bool,
    config: &Config,
) -> Result<ExitCode, ExitError> {
    let source = read_source(path)?;
    let parsed = parse_or(path, &source)?;
    let symbols = ctx_symbol::extract_symbols(&parsed);
    let file_tokens = tokens(&source);
    let show_doc = config.outline.show_doc && !no_doc;

    // Parse failures are signaled, not hidden: tree-sitter recovers, so the
    // partial symbol list is still delivered, but the JSON envelope gains a
    // `parse_error` field, text mode prints a warning on stderr, and the
    // exit code is 3 (§4.1) so agents can tell "no symbols" from "broken
    // syntax".
    let parse_errors = ctx_symbol::parse_error_count(&parsed);
    let parse_failed = parse_errors > 0;

    if format == Format::Json {
        let entries: Vec<serde_json::Value> = symbols
            .iter()
            .map(|s| symbol_entry(s, !show_doc, no_lines))
            .collect();
        let mut payload = json!({
            "schema_version": 1,
            "tool": "outline",
            "path": path.display().to_string(),
            "language": parsed.language.name(),
            "symbols": entries,
        });
        if parse_failed {
            payload["parse_error"] = json!({
                "count": parse_errors,
                "message": "tree-sitter reported syntax errors; symbol list may be incomplete",
            });
        }
        if show_saved {
            // `tokens_after` counts the bytes actually delivered (the
            // serialized payload), not a sum of symbol slice estimates.
            let delivered_tokens = tokens(&payload.to_string());
            payload["saved"] = json!({
                "tokens_before": file_tokens,
                "tokens_after": delivered_tokens,
                "percent": saved_pct(file_tokens, delivered_tokens),
            });
        }
        println!("{payload}");
        return Ok(if parse_failed {
            ExitCode::from(3)
        } else {
            ExitCode::SUCCESS
        });
    }

    // [outline] fold_threshold (§7): fold the symbol list in text mode when it
    // exceeds the threshold. JSON stays complete (machine contract).
    let fold_limit = config.outline.fold_threshold;
    let folded = symbols.len() > fold_limit;
    let shown: &[Symbol] = if folded {
        &symbols[..fold_limit]
    } else {
        &symbols
    };

    let mut body = String::new();
    if !shown.is_empty() {
        let name_w = shown
            .iter()
            .map(|s| s.name.len())
            .max()
            .unwrap_or(0)
            .max(10);
        for s in shown {
            let loc = if no_lines {
                String::new()
            } else if s.start_line == s.end_line {
                format!("L:{}", s.start_line)
            } else {
                format!("L:{}-{}", s.start_line, s.end_line)
            };
            body.push_str(&format!(
                "  {:<7} {:<name_w$} {:<9}    {}\n",
                kind_alias(s.kind),
                s.name,
                loc,
                s.signature,
            ));
        }
    }
    if folded {
        body.push_str(&format!(
            "  ... [{} symbols omitted]\n",
            symbols.len() - fold_limit
        ));
    }

    // `tokens_after` measures the bytes actually delivered (the symbol list
    // render), not a sum of symbol slice estimates — nested definitions used
    // to be double-counted, inflating the estimate beyond the file itself.
    let delivered_tokens = tokens(&body);
    let saved = saved_pct(file_tokens, delivered_tokens);
    let header = if show_saved {
        format!(
            "# {}  [{} symbols, {} -> {} tokens, saved ~{}%]",
            path.display(),
            symbols.len(),
            human_bytes(source.len()),
            group(delivered_tokens),
            saved,
        )
    } else {
        format!("# {}  [{} symbols]", path.display(), symbols.len())
    };
    print!("{header}\n{body}");
    if parse_failed {
        eprintln!(
            "warning: parse failed ({} error node(s)); symbol list may be incomplete",
            parse_errors
        );
    }
    Ok(if parse_failed {
        ExitCode::from(3)
    } else {
        ExitCode::SUCCESS
    })
}

fn run_symbol(
    path: &Path,
    name: &str,
    signature_only: bool,
    compact: bool,
    subrange: Option<&str>,
    format: Format,
    show_saved: bool,
) -> Result<ExitCode, ExitError> {
    let source = read_source(path)?;
    let parsed = parse_or(path, &source)?;
    let symbols = ctx_symbol::extract_symbols(&parsed);
    let symbol = symbols
        .iter()
        .find(|s| s.name == name)
        .ok_or_else(|| ExitError::new(4, format!("symbol not found: {name}")))?;
    let body = slice_text(&source, &symbol.byte_range)?;
    let slice = if compact {
        ctx_symbol::compact_symbol(&parsed, symbol)
    } else if signature_only {
        symbol.signature.clone()
    } else if let Some(range) = subrange {
        slice_lines(&body, range).map_err(|e| ExitError::new(2, e))?
    } else {
        body
    };
    let file_tokens = tokens(&source);
    let delivered_tokens = tokens(&slice);
    let saved = saved_pct(file_tokens, delivered_tokens);

    if format == Format::Json {
        let mut payload = json!({
            "schema_version": 1,
            "tool": "symbol",
            "path": path.display().to_string(),
            "language": parsed.language.name(),
            "name": symbol.name,
            "symbol": symbol_entry(symbol, false, false),
        });
        if compact {
            payload["compact"] = json!(slice);
        } else {
            payload["slice"] = json!(slice);
        }
        if show_saved {
            payload["saved"] = json!({
                "tokens_before": file_tokens,
                "tokens_after": delivered_tokens,
                "percent": saved,
            });
        }
        println!("{payload}");
        return Ok(ExitCode::SUCCESS);
    }

    let loc = if symbol.start_line == symbol.end_line {
        format!("{}:{}", path.display(), symbol.start_line)
    } else {
        format!(
            "{}:{}-{}",
            path.display(),
            symbol.start_line,
            symbol.end_line
        )
    };
    if show_saved {
        println!(
            "# {}  {}  ({} tokens, saved ~{}%)",
            symbol.name,
            loc,
            group(delivered_tokens),
            saved,
        );
    } else {
        println!("# {}  {}", symbol.name, loc);
    }
    println!("{slice}");
    Ok(ExitCode::SUCCESS)
}

fn run_read(
    path: &Path,
    raw: &str,
    format: Format,
    show_saved: bool,
) -> Result<ExitCode, ExitError> {
    let source = read_source(path)?;
    // Split on `\n` keeping the endings so CRLF slices stay verbatim
    // (byte-stability plus original line-ending fidelity).
    let file_lines: Vec<&str> = source.split_inclusive('\n').collect();
    let ranges = parse_ranges(raw).map_err(|e| ExitError::new(2, e))?;
    let ranges: Vec<(usize, usize)> = clamp_open_ends(ranges, file_lines.len());
    for (start, end) in &ranges {
        if *start > file_lines.len() {
            return Err(ExitError::new(
                2,
                format!(
                    "line range {start}-{end} out of bounds (file has {} lines)",
                    file_lines.len()
                ),
            ));
        }
    }
    let slices: Vec<(usize, usize, String)> = ranges
        .iter()
        .map(|(start, end)| (*start, *end, file_lines[start - 1..*end].concat()))
        .collect();
    let delivered_tokens: usize = slices.iter().map(|(_, _, text)| tokens(text)).sum();
    let file_tokens = tokens(&source);
    let saved = saved_pct(file_tokens, delivered_tokens);

    if format == Format::Json {
        let ranges_json: Vec<serde_json::Value> = slices
            .iter()
            .map(
                |(start, end, text)| json!({ "start_line": start, "end_line": end, "slice": text }),
            )
            .collect();
        let mut payload = json!({
            "schema_version": 1,
            "tool": "read",
            "path": path.display().to_string(),
            "ranges": ranges_json,
        });
        if show_saved {
            payload["saved"] = json!({
                "tokens_before": file_tokens,
                "tokens_after": delivered_tokens,
                "percent": saved,
            });
        }
        println!("{payload}");
        return Ok(ExitCode::SUCCESS);
    }

    for (start, end, text) in &slices {
        println!("# {}:{}-{}", path.display(), start, end);
        println!("{text}");
    }
    if show_saved {
        println!(
            "Saved ~{}% ({} -> {} tokens)",
            saved,
            group(file_tokens),
            group(delivered_tokens),
        );
    }
    Ok(ExitCode::SUCCESS)
}

fn run_exec(
    cmd: &str,
    keep: &[String],
    head: Option<usize>,
    tail: Option<usize>,
    format: Format,
    show_saved: bool,
    config: &Config,
) -> Result<ExitCode, ExitError> {
    let words = shell_words::split(cmd)
        .map_err(|e| ExitError::new(1, format!("invalid command line: {e}")))?;
    if words.is_empty() {
        return Err(ExitError::new(1, "empty command"));
    }
    let output = StdCommand::new(&words[0])
        .args(&words[1..])
        .output()
        .map_err(|e| ExitError::new(1, format!("failed to run `{cmd}`: {e}")))?;

    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);
    let mut raw = stdout.to_string();
    if !stdout.is_empty() && !stderr.is_empty() && !stdout.ends_with('\n') {
        raw.push('\n');
    }
    raw.push_str(&stderr);

    let mut options = ctx_exec::CompressOptions {
        keep_patterns: config.exec.keep.clone(),
        head_lines: config.exec.head_lines,
        tail_lines: config.exec.tail_lines,
        collapse_threshold: config.exec.collapse_threshold,
    };
    options.keep_patterns.extend(keep.iter().cloned());
    if let Some(head) = head {
        options.head_lines = head;
    }
    if let Some(tail) = tail {
        options.tail_lines = tail;
    }

    let result =
        ctx_exec::compress(&raw, &options).map_err(|e| ExitError::new(1, e.to_string()))?;
    let stats = result.stats;
    let code = exit_code(&output.status);

    if format == Format::Json {
        let mut payload = json!({
            "schema_version": 1,
            "tool": "exec",
            "cmd": cmd,
            "exit_code": code,
            "compressed": result.text,
        });
        if show_saved {
            payload["saved"] = json!({
                "tokens_before": stats.original_tokens,
                "tokens_after": stats.compressed_tokens,
                "percent": stats.saved_percent,
            });
        }
        println!("{payload}");
        return Ok(ExitCode::from(code as u8));
    }

    println!("$ {cmd}");
    if !result.text.is_empty() {
        println!("{}", result.text);
    }
    if show_saved {
        println!(
            "Saved ~{}% ({} -> {} tokens)",
            stats.saved_percent,
            group(stats.original_tokens),
            group(stats.compressed_tokens),
        );
    }
    Ok(ExitCode::from(code as u8))
}

fn run_deps(
    path: &Path,
    format: Format,
    show_saved: bool,
    config: &Config,
) -> Result<ExitCode, ExitError> {
    let source = read_source(path)?;
    let parsed = parse_or(path, &source)?;
    let imports = ctx_symbol::extract_imports(&parsed);
    let file_dir = path.parent().unwrap_or(Path::new("."));
    let resolved = deps::resolve(
        &imports,
        parsed.language.name(),
        file_dir,
        &config.paths.ignore,
    );
    let file_tokens = tokens(&source);
    let delivered_tokens: usize = resolved.iter().map(|r| r.bytes / 4).sum();
    let saved = saved_pct(file_tokens, delivered_tokens);

    if format == Format::Json {
        let entries: Vec<serde_json::Value> = resolved
            .iter()
            .map(|r| json!({ "target": r.target, "kind": r.kind, "line": r.line }))
            .collect();
        let mut payload = json!({
            "schema_version": 1,
            "tool": "deps",
            "path": path.display().to_string(),
            "language": parsed.language.name(),
            "imports": entries,
        });
        if show_saved {
            payload["saved"] = json!({
                "tokens_before": file_tokens,
                "tokens_after": delivered_tokens,
                "percent": saved,
            });
        }
        println!("{payload}");
        return Ok(ExitCode::SUCCESS);
    }

    let header = if show_saved {
        format!(
            "# {}  [{} imports, {} -> {} tokens, saved ~{}%]",
            path.display(),
            resolved.len(),
            human_bytes(source.len()),
            group(delivered_tokens),
            saved,
        )
    } else {
        format!("# {}  [{} imports]", path.display(), resolved.len())
    };
    println!("{header}");
    if !resolved.is_empty() {
        let name_w = resolved
            .iter()
            .map(|r| r.target.len())
            .max()
            .unwrap_or(0)
            .max(10);
        for r in &resolved {
            println!(
                "  {:<9} {:<name_w$}    L:{}",
                dep_kind_name(r.kind),
                r.target,
                r.line,
            );
        }
    }
    Ok(ExitCode::SUCCESS)
}

fn dep_kind_name(kind: deps::DepKind) -> &'static str {
    match kind {
        deps::DepKind::Local => "local",
        deps::DepKind::External => "external",
        deps::DepKind::Ignored => "ignored",
    }
}

/// Child exit code with the conventional signal encoding: 128 + signal when
/// the child was killed by one (otherwise the code is `None` and 1 is used).
fn exit_code(status: &std::process::ExitStatus) -> i32 {
    #[cfg(unix)]
    {
        use std::os::unix::process::ExitStatusExt;
        if let Some(sig) = status.signal() {
            return 128 + sig;
        }
    }
    status.code().unwrap_or(1)
}

fn read_source(path: &Path) -> Result<String, ExitError> {
    std::fs::read_to_string(path)
        .map_err(|e| ExitError::new(1, format!("failed to read {}: {e}", path.display())))
}

fn parse_or(path: &Path, source: &str) -> Result<ParsedSource, ExitError> {
    ctx_symbol::parse(path, source).map_err(|e| match e {
        ctx_symbol::SymbolError::UnsupportedLanguage(p) => {
            ExitError::new(2, format!("unsupported extension: {p}"))
        }
        ctx_symbol::SymbolError::Parse(m) => ExitError::new(3, format!("parse failure: {m}")),
        ctx_symbol::SymbolError::Io(e) => ExitError::new(1, e.to_string()),
        ctx_symbol::SymbolError::NotFound(n) => ExitError::new(4, format!("symbol not found: {n}")),
    })
}

fn slice_text(source: &str, range: &std::ops::Range<usize>) -> Result<String, ExitError> {
    let bytes = source
        .as_bytes()
        .get(range.clone())
        .ok_or_else(|| ExitError::new(3, "symbol byte range out of bounds"))?;
    std::str::from_utf8(bytes)
        .map(|s| s.to_string())
        .map_err(|e| ExitError::new(3, format!("symbol slice is not valid UTF-8: {e}")))
}

/// Slice 1-based inclusive line numbers out of a multi-line text.
fn slice_lines(text: &str, range: &str) -> Result<String, String> {
    let ranges = parse_ranges(range)?;
    if ranges.len() > 1 {
        return Err("symbol --lines accepts a single range (e.g. 3-10)".to_string());
    }
    let lines: Vec<&str> = text.split_inclusive('\n').collect();
    let (start, end) = clamp_open_ends(ranges, lines.len())[0];
    if start > lines.len() {
        return Err(format!(
            "line range {start}-{end} out of bounds (symbol has {} lines)",
            lines.len()
        ));
    }
    Ok(lines[start - 1..end].concat())
}

/// Resolve open-ended ranges (`10-`) to an explicit end within `limit`.
fn clamp_open_ends(ranges: Vec<(usize, usize)>, limit: usize) -> Vec<(usize, usize)> {
    ranges
        .into_iter()
        .map(|(start, end)| (start, end.min(limit)))
        .collect()
}

/// Parse comma-separated, 1-based inclusive ranges: `100-150,200-210`, `42`,
/// or `10-` (open-ended). The end of an open range resolves to `usize::MAX`
/// and is clamped by the caller.
fn parse_ranges(raw: &str) -> Result<Vec<(usize, usize)>, String> {
    let tokens: Vec<&str> = raw
        .split(',')
        .map(str::trim)
        .filter(|t| !t.is_empty())
        .collect();
    if tokens.is_empty() {
        return Err("empty line range".to_string());
    }
    tokens.iter().map(|tok| parse_range(tok)).collect()
}

fn parse_range(tok: &str) -> Result<(usize, usize), String> {
    let (start_s, end_s) = match tok.split_once('-') {
        Some((s, e)) => (s.trim(), e.trim()),
        None => (tok, tok),
    };
    let start: usize = start_s
        .parse()
        .map_err(|_| format!("invalid range `{tok}`"))?;
    if start == 0 {
        return Err("ranges are 1-based; start must be >= 1".to_string());
    }
    let end: usize = if end_s.is_empty() {
        usize::MAX
    } else {
        end_s
            .parse()
            .map_err(|_| format!("invalid range `{tok}`"))?
    };
    if start > end {
        return Err(format!("range {start}-{end} is inverted"));
    }
    Ok((start, end))
}

/// JSON symbol entry per the outline contract (§4.1).
fn symbol_entry(symbol: &Symbol, no_doc: bool, no_lines: bool) -> serde_json::Value {
    let mut entry = json!({
        "name": symbol.name,
        "kind": kind_name(symbol.kind),
        "signature": symbol.signature,
    });
    if !no_lines {
        entry["start_line"] = json!(symbol.start_line);
        entry["end_line"] = json!(symbol.end_line);
    }
    if !no_doc && let Some(doc) = &symbol.doc_comment {
        entry["doc_comment"] = json!(doc);
    }
    entry
}

fn kind_name(kind: SymbolKind) -> &'static str {
    match kind {
        SymbolKind::Class => "class",
        SymbolKind::Function => "function",
        SymbolKind::Method => "method",
        SymbolKind::Struct => "struct",
        SymbolKind::Enum => "enum",
        SymbolKind::Interface => "interface",
        SymbolKind::Const => "const",
        SymbolKind::Variable => "var",
        SymbolKind::Trait => "trait",
        SymbolKind::Type => "type",
        SymbolKind::Module => "module",
    }
}

fn kind_alias(kind: SymbolKind) -> &'static str {
    match kind {
        SymbolKind::Class => "class",
        SymbolKind::Function => "fn",
        SymbolKind::Method => "method",
        SymbolKind::Struct => "struct",
        SymbolKind::Enum => "enum",
        SymbolKind::Interface => "interface",
        SymbolKind::Const => "const",
        SymbolKind::Variable => "var",
        SymbolKind::Trait => "trait",
        SymbolKind::Type => "type",
        SymbolKind::Module => "mod",
    }
}

/// Token approximation: 4 bytes ~ 1 token (cli-contract.md §8).
fn tokens(text: &str) -> usize {
    text.len() / 4
}

fn saved_pct(before: usize, after: usize) -> u32 {
    if before == 0 {
        return 0;
    }
    ((before - after.min(before)) * 100 / before) as u32
}

fn human_bytes(n: usize) -> String {
    if n < 1024 {
        format!("~{} B", n)
    } else {
        format!("~{:.1} KB", n as f64 / 1024.0)
    }
}

fn group(n: usize) -> String {
    let digits = n.to_string();
    let bytes = digits.as_bytes();
    let mut out = String::with_capacity(digits.len() + 2);
    for (i, b) in bytes.iter().enumerate() {
        if i > 0 && (bytes.len() - i).is_multiple_of(3) {
            out.push(',');
        }
        out.push(*b as char);
    }
    out
}