logcut 0.3.0

Local-first stacktrace, runtime log & compiler error slicing for AI coding agents and terminal pipelines
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
use std::fs;
use std::io::{self, IsTerminal, Read, Write};
#[cfg(feature = "cli")]
use std::path::Path;
use std::path::PathBuf;

use anyhow::Result;
use clap::{Args, Parser, Subcommand};

use logcut::core::{
    self,
    models::{
        SliceBuildArgs, SliceBuildReport, SliceContainerRequest, SliceLogRequest, SliceReport,
        SliceServiceRequest, SliceTestArgs, SliceTestReport, WatchRequest,
    },
};

#[derive(Parser)]
#[command(
    name = "logcut",
    version,
    about = "Local-first stacktrace and runtime log slicer"
)]
struct Cli {
    #[command(subcommand)]
    command: Commands,
    /// Print JSON statistics to stderr
    #[arg(long, global = true)]
    stats: bool,
}

#[derive(Subcommand)]
enum Commands {
    /// Slice a log file, piped output, or inline text
    Slice(SliceArgs),
    /// Collapse compiler error cascades from a build log or piped output
    Build(BuildArgs),
    /// Strip passing test lines and keep failures with source context
    Test(TestArgs),
    /// Run a command, stream its output, and save a crash report on failure
    Watch(WatchCliArgs),
    /// Slice Docker container logs
    Docker(DockerArgs),
    /// Slice a systemd unit's journal
    Journal(JournalArgs),
    /// Ask an OpenAI-compatible model using logcut tools
    Ask(AskArgs),
    /// Serve the MCP protocol over stdio
    Mcp,
    /// Install MCP config and /debug-log commands for AI hosts
    Init(InitArgs),
}

#[derive(Args)]
struct SliceArgs {
    file: Option<PathBuf>,
    #[arg(long)]
    raw_text: Option<String>,
    #[arg(long, default_value = ".")]
    workspace_root: String,
    #[arg(long)]
    tail_lines: Option<usize>,
    #[arg(long)]
    context_lines: Option<usize>,
    #[arg(long)]
    include_vendor_frames: bool,
    #[arg(long)]
    max_chars: Option<usize>,
    #[arg(long)]
    min_level: Option<String>,
    #[arg(long = "where")]
    where_filters: Vec<String>,
}

#[derive(Args)]
struct TestArgs {
    file: Option<PathBuf>,
    #[arg(long)]
    raw_text: Option<String>,
    #[arg(long, default_value = ".")]
    workspace_root: String,
    #[arg(long)]
    tail_lines: Option<usize>,
    #[arg(long)]
    context_lines: Option<usize>,
    #[arg(long)]
    max_chars: Option<usize>,
}

#[derive(Args)]
struct WatchCliArgs {
    /// Command and arguments after `--`, never interpreted by a shell
    #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
    command: Vec<String>,
    #[arg(long, default_value = ".")]
    workspace_root: String,
    #[arg(long)]
    ring_lines: Option<usize>,
    #[arg(long)]
    max_chars: Option<usize>,
}

#[derive(Args)]
struct BuildArgs {
    file: Option<PathBuf>,
    #[arg(long)]
    workspace_root: Option<String>,
    #[arg(long)]
    tail_lines: Option<usize>,
    #[arg(long)]
    max_errors: Option<usize>,
    #[arg(long)]
    context_lines: Option<usize>,
    #[arg(long)]
    max_chars: Option<usize>,
}

#[derive(Args)]
struct DockerArgs {
    container: String,
    #[arg(long)]
    tail_lines: Option<usize>,
    #[arg(long)]
    since: Option<String>,
    #[arg(long, default_value = ".")]
    workspace_root: String,
    #[arg(long)]
    max_chars: Option<usize>,
}

#[derive(Args)]
struct JournalArgs {
    unit: String,
    #[arg(long)]
    lines: Option<usize>,
    #[arg(long, default_value = ".")]
    workspace_root: String,
    #[arg(long)]
    max_chars: Option<usize>,
}

#[derive(Args)]
struct AskArgs {
    question: Vec<String>,
    #[arg(long, default_value = ".")]
    workspace_root: String,
}

#[derive(Args)]
struct InitArgs {
    #[arg(long)]
    opencode: bool,
    #[arg(long)]
    claude: bool,
    #[arg(long)]
    cursor: bool,
    #[arg(long)]
    all: bool,
}

fn emit(report: SliceReport, show_stats: bool) -> Result<()> {
    if show_stats {
        writeln!(io::stderr(), "{}", serde_json::to_string(&report.stats)?)?;
    }
    println!("{}", report.text);
    Ok(())
}

fn emit_build(report: SliceBuildReport, show_stats: bool) -> Result<()> {
    if show_stats {
        writeln!(io::stderr(), "{}", serde_json::to_string(&report.stats)?)?;
    }
    println!("{}", report.text);
    Ok(())
}

fn emit_test(report: SliceTestReport, show_stats: bool) -> Result<()> {
    if show_stats {
        writeln!(io::stderr(), "{}", serde_json::to_string(&report.stats)?)?;
    }
    println!("{}", report.text);
    Ok(())
}

fn piped_stdin() -> Result<Option<String>> {
    if io::stdin().is_terminal() {
        return Ok(None);
    }
    let mut text = String::new();
    io::stdin().read_to_string(&mut text)?;
    Ok(Some(text))
}

const SLASH_COMMAND: &str = "---\ndescription: Slice logs and stacktraces with logcut\n---\n\
Inspect $ARGUMENTS: pipe failing command output or a log file into `logcut slice`, \
then summarize the surviving stack frames and deduplicated error bursts. \
Use `logcut mcp` tools when available.\n";

fn init_documents(args: &InitArgs) -> Vec<(&'static str, String)> {
    let server = r#"{"type":"stdio","command":"logcut","args":["mcp"],"description":"Run logcut mcp over stdio"}"#;
    let mut documents = Vec::new();
    let opencode = args.opencode || args.all;
    let claude = args.claude || args.all;
    let cursor = args.cursor || args.all;

    if opencode {
        documents.push((
            "opencode.json",
            r#"{"$schema":"https://opencode.ai/config.json","mcp":{"servers":{"logcut":{"type":"local","command":["logcut","mcp"]}}}}"#.to_owned(),
        ));
        documents.push((".opencode/commands/debug-log.md", SLASH_COMMAND.to_owned()));
    }
    if claude {
        documents.push((
            ".mcp.json",
            format!(r#"{{"mcpServers":{{"logcut":{server}}}}}"#),
        ));
        documents.push((".claude/commands/debug-log.md", SLASH_COMMAND.to_owned()));
    }
    if cursor {
        documents.push((
            ".cursor/mcp.json",
            format!(r#"{{"mcpServers":{{"logcut":{server}}}}}"#),
        ));
        documents.push((
            ".cursor/rules/debug-log.mdc",
            format!(
                "---\ndescription: Debug logs with logcut\nalwaysApply: false\n---\n{SLASH_COMMAND}"
            ),
        ));
    }
    documents
}

fn write_documents(documents: &[(&str, String)]) -> Result<()> {
    let base = std::env::current_dir()?;
    for (relative, contents) in documents {
        let path = base.join(relative);
        if path.exists() {
            eprintln!("logcut init: keeping existing {}", path.display());
            continue;
        }
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent)?;
        }
        fs::write(&path, contents)?;
        eprintln!("logcut init: wrote {}", path.display());
    }
    Ok(())
}

#[tokio::main]
async fn main() -> Result<()> {
    let cli = Cli::parse();

    // Diagnostics never share stdout with JSON-RPC or piped reports.
    tracing_subscriber::fmt()
        .with_ansi(false)
        .with_writer(io::stderr)
        .with_max_level(tracing::Level::INFO)
        .init();

    match cli.command {
        Commands::Mcp => {
            #[cfg(feature = "mcp")]
            {
                // Only JSON-RPC may reach stdout in this mode.
                logcut::mcp::serve().await?;
                Ok(())
            }
            #[cfg(not(feature = "mcp"))]
            anyhow::bail!("this build does not include the mcp feature")
        }
        Commands::Slice(args) => {
            let piped =
                if args.file.is_none() && args.raw_text.is_none() && !io::stdin().is_terminal() {
                    let mut text = String::new();
                    io::stdin().read_to_string(&mut text)?;
                    Some(text)
                } else {
                    None
                };
            let report = core::slice_log(SliceLogRequest {
                path: args.file.map(|path| path.to_string_lossy().into_owned()),
                raw_text: args.raw_text.or(piped),
                workspace_root: Some(args.workspace_root),
                tail_lines: args.tail_lines,
                context_lines: args.context_lines,
                include_vendor_frames: Some(args.include_vendor_frames),
                max_chars: args.max_chars,
                min_level: args.min_level,
                where_filters: args.where_filters,
            })?;
            emit(report, cli.stats)
        }
        Commands::Test(args) => {
            let raw_text = if args.file.is_none() && args.raw_text.is_none() {
                piped_stdin()?
            } else {
                None
            };
            let report = core::slice_test(SliceTestArgs {
                path: args.file.map(|path| path.to_string_lossy().into_owned()),
                raw_text: args.raw_text.or(raw_text),
                workspace_root: Some(args.workspace_root),
                tail_lines: args.tail_lines,
                context_lines: args.context_lines,
                max_chars: args.max_chars,
            })?;
            emit_test(report, cli.stats)
        }
        Commands::Watch(args) => {
            let mut request = WatchRequest {
                command: args.command,
                workspace_root: args.workspace_root,
                ..Default::default()
            };
            if let Some(ring_lines) = args.ring_lines {
                request.ring_lines = ring_lines;
            }
            if let Some(max_chars) = args.max_chars {
                request.max_chars = max_chars;
            }
            let mut sink = |is_stderr: bool, line: &str| {
                if is_stderr {
                    eprintln!("{line}");
                } else {
                    println!("{line}");
                }
            };
            let report = core::watch::watch(request, Some(&mut sink)).await?;
            if report.detected {
                println!("{}", report.text);
                writeln!(
                    io::stderr(),
                    "logcut watch: crash report saved to {}",
                    report.path
                )?;
            } else {
                writeln!(
                    io::stderr(),
                    "logcut watch: command exited {:?} without a detected crash",
                    report.exit_code
                )?;
            }
            Ok(())
        }
        Commands::Build(args) => {
            let raw_text = if args.file.is_none() {
                piped_stdin()?
            } else {
                None
            };
            let report = core::slice_build(SliceBuildArgs {
                path: args.file.map(|path| path.to_string_lossy().into_owned()),
                raw_text,
                workspace_root: args.workspace_root,
                tail_lines: args.tail_lines,
                max_errors: args.max_errors,
                context_lines: args.context_lines,
                max_chars: args.max_chars,
            })?;
            emit_build(report, cli.stats)
        }
        Commands::Docker(args) => {
            let report = core::slice_container(SliceContainerRequest {
                container: args.container,
                tail_lines: args.tail_lines,
                since: args.since,
                workspace_root: Some(args.workspace_root),
                max_chars: args.max_chars,
            })
            .await?;
            emit(report, cli.stats)
        }
        Commands::Journal(args) => {
            let report = core::slice_service(SliceServiceRequest {
                unit: args.unit,
                lines: args.lines,
                workspace_root: Some(args.workspace_root),
                max_chars: args.max_chars,
            })
            .await?;
            emit(report, cli.stats)
        }
        Commands::Ask(args) => {
            #[cfg(feature = "cli")]
            {
                let answer =
                    logcut::agent::ask(&args.question.join(" "), Path::new(&args.workspace_root))
                        .await?;
                println!("{answer}");
                Ok(())
            }
            #[cfg(not(feature = "cli"))]
            {
                let _ = args;
                anyhow::bail!("this build does not include the cli feature")
            }
        }
        Commands::Init(args) => {
            let args = if !args.opencode && !args.claude && !args.cursor && !args.all {
                InitArgs {
                    opencode: true,
                    claude: true,
                    cursor: true,
                    all: true,
                }
            } else {
                args
            };
            write_documents(&init_documents(&args))
        }
    }
}