prx 0.5.9

Praxis — agent-native Unix tools. Single binary replacing grep, cat, find, sed, diff 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
use std::path::Path;

use clap::Args;
use serde::Serialize;
use similar::ChangeTag;

use crate::output::AgError;
use crate::parsing::outline;

#[derive(Args)]
pub struct DiffArgs {
    /// File path (optional, default: all changed files)
    pub file: Option<String>,

    /// Compare against git ref
    #[arg(long, default_value = "HEAD")]
    pub since: String,

    /// Compare staged changes
    #[arg(long)]
    pub staged: bool,

    /// Summary and stats only
    #[arg(long)]
    pub stat_only: bool,

    /// Token budget for hunks
    #[arg(long)]
    pub budget: Option<usize>,

    /// Group hunks by function
    #[arg(long)]
    pub functions: bool,
}

#[derive(Serialize, serde::Deserialize, Debug)]
pub struct DiffOutput {
    pub summary: String,
    pub stats: DiffStats,
    pub semantic_notes: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub hunks: Option<Vec<Hunk>>,
}

#[derive(Serialize, serde::Deserialize, Debug)]
pub struct DiffStats {
    pub additions: usize,
    pub deletions: usize,
    pub files_changed: usize,
    pub functions_changed: Vec<String>,
}

#[derive(Serialize, serde::Deserialize, Debug)]
pub struct Hunk {
    pub file: String,
    pub function: Option<String>,
    pub changes: Vec<DiffChange>,
}

#[derive(Serialize, serde::Deserialize, Debug)]
pub struct DiffChange {
    #[serde(rename = "type")]
    pub change_type: String,
    pub old: Option<String>,
    pub new: Option<String>,
}

pub fn run(args: DiffArgs) -> Result<serde_json::Value, AgError> {
    let changed_files = get_git_diff(&args)?;

    if changed_files.is_empty() {
        let output = DiffOutput {
            summary: "no changes".to_string(),
            stats: DiffStats {
                additions: 0,
                deletions: 0,
                files_changed: 0,
                functions_changed: vec![],
            },
            semantic_notes: vec![],
            hunks: None,
        };
        return to_json(output);
    }

    let mut total_additions = 0;
    let mut total_deletions = 0;
    let mut all_hunks = Vec::new();
    let mut all_functions_changed = Vec::new();
    let mut semantic_notes = Vec::new();

    for file_diff in &changed_files {
        let diff = similar::TextDiff::from_lines(&file_diff.old_content, &file_diff.new_content);
        let mut file_additions = 0;
        let mut file_deletions = 0;
        let mut file_changes = Vec::new();

        for change in diff.iter_all_changes() {
            match change.tag() {
                ChangeTag::Insert => {
                    file_additions += 1;
                    file_changes.push(DiffChange {
                        change_type: "addition".to_string(),
                        old: None,
                        new: Some(change.to_string().trim_end().to_string()),
                    });
                }
                ChangeTag::Delete => {
                    file_deletions += 1;
                    file_changes.push(DiffChange {
                        change_type: "deletion".to_string(),
                        old: Some(change.to_string().trim_end().to_string()),
                        new: None,
                    });
                }
                ChangeTag::Equal => {}
            }
        }

        total_additions += file_additions;
        total_deletions += file_deletions;

        let ext = Path::new(&file_diff.path)
            .extension()
            .and_then(|e| e.to_str());

        let functions_in_diff = if let Some(ext_str) = ext {
            find_changed_functions(&file_diff.old_content, &file_diff.new_content, ext_str)
        } else {
            vec![]
        };

        all_functions_changed.extend(
            functions_in_diff
                .iter()
                .map(|f| format!("{}:{}", file_diff.path, f)),
        );

        detect_semantic_changes(
            &file_diff.old_content,
            &file_diff.new_content,
            ext,
            &file_diff.path,
            &mut semantic_notes,
        );

        if !file_changes.is_empty() {
            all_hunks.push(Hunk {
                file: file_diff.path.clone(),
                function: functions_in_diff.first().cloned(),
                changes: file_changes,
            });
        }
    }

    let summary = build_summary(
        changed_files.len(),
        total_additions,
        total_deletions,
        &all_functions_changed,
    );

    let hunks = if args.stat_only {
        None
    } else {
        let mut h = all_hunks;
        if let Some(budget) = args.budget {
            let mut used = 0;
            h.retain(|hunk| {
                let cost = hunk
                    .changes
                    .iter()
                    .map(|c| {
                        c.old.as_ref().map_or(0, |s| s.len())
                            + c.new.as_ref().map_or(0, |s| s.len())
                    })
                    .sum::<usize>()
                    / 4;
                if used + cost <= budget {
                    used += cost;
                    true
                } else {
                    false
                }
            });
        }
        Some(h)
    };

    let output = DiffOutput {
        summary,
        stats: DiffStats {
            additions: total_additions,
            deletions: total_deletions,
            files_changed: changed_files.len(),
            functions_changed: all_functions_changed,
        },
        semantic_notes,
        hunks,
    };

    to_json(output)
}

struct FileDiff {
    path: String,
    old_content: String,
    new_content: String,
}

fn get_git_diff(args: &DiffArgs) -> Result<Vec<FileDiff>, AgError> {
    let diff_args = if args.staged {
        vec!["diff", "--staged", "--name-only"]
    } else {
        vec!["diff", &args.since, "--name-only"]
    };

    let output = std::process::Command::new("git")
        .args(&diff_args)
        .output()
        .map_err(|e| AgError::GitError {
            message: format!("failed to run git: {e}"),
        })?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(AgError::GitError {
            message: format!("git diff failed: {stderr}"),
        });
    }

    let names = String::from_utf8_lossy(&output.stdout);
    let mut diffs = Vec::new();

    for name in names.lines().filter(|l| !l.is_empty()) {
        if let Some(ref file_filter) = args.file {
            if !name.contains(file_filter) {
                continue;
            }
        }

        let old_content = get_git_file_content(name, &args.since).unwrap_or_default();
        let new_content = std::fs::read_to_string(name).unwrap_or_default();

        diffs.push(FileDiff {
            path: name.to_string(),
            old_content,
            new_content,
        });
    }

    Ok(diffs)
}

fn get_git_file_content(path: &str, git_ref: &str) -> Option<String> {
    let output = std::process::Command::new("git")
        .args(["show", &format!("{git_ref}:{path}")])
        .output()
        .ok()?;

    if output.status.success() {
        Some(String::from_utf8_lossy(&output.stdout).to_string())
    } else {
        None
    }
}

fn find_changed_functions(old: &str, new: &str, ext: &str) -> Vec<String> {
    let symbols = outline::extract_symbols(new, ext);
    let diff = similar::TextDiff::from_lines(old, new);
    let mut changed_lines: Vec<usize> = Vec::new();

    let mut line_num = 0;
    for change in diff.iter_all_changes() {
        if change.tag() == ChangeTag::Equal {
            line_num += 1;
        } else if change.tag() == ChangeTag::Insert {
            line_num += 1;
            changed_lines.push(line_num);
        }
    }

    let mut functions = Vec::new();
    for line in &changed_lines {
        for sym in &symbols {
            if *line >= sym.start_line && *line <= sym.end_line && !functions.contains(&sym.name) {
                functions.push(sym.name.clone());
            }
        }
    }

    functions
}

fn detect_semantic_changes(
    old: &str,
    new: &str,
    ext: Option<&str>,
    path: &str,
    notes: &mut Vec<String>,
) {
    let ext_str = match ext {
        Some(e) => e,
        None => return,
    };

    let old_symbols = outline::extract_symbols(old, ext_str);
    let new_symbols = outline::extract_symbols(new, ext_str);

    let old_names: Vec<&str> = old_symbols.iter().map(|s| s.name.as_str()).collect();
    let new_names: Vec<&str> = new_symbols.iter().map(|s| s.name.as_str()).collect();

    for name in &new_names {
        if !old_names.contains(name) {
            notes.push(format!("{path}: new symbol `{name}`"));
        }
    }

    for name in &old_names {
        if !new_names.contains(name) {
            notes.push(format!("{path}: removed symbol `{name}`"));
        }
    }

    for old_sym in &old_symbols {
        if let Some(new_sym) = new_symbols.iter().find(|s| s.name == old_sym.name) {
            if old_sym.signature != new_sym.signature {
                notes.push(format!("{path}: signature changed `{}`", old_sym.name));
            }
        }
    }
}

fn build_summary(files: usize, additions: usize, deletions: usize, functions: &[String]) -> String {
    let func_part = if functions.is_empty() {
        String::new()
    } else if functions.len() <= 3 {
        format!(". Functions: {}", functions.join(", "))
    } else {
        format!(". {} functions changed", functions.len())
    };

    format!(
        "{} file(s) changed, +{} -{}{func_part}",
        files, additions, deletions
    )
}

fn to_json(output: DiffOutput) -> Result<serde_json::Value, AgError> {
    serde_json::to_value(output).map_err(|e| AgError::Internal {
        message: e.to_string(),
    })
}

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

    #[test]
    fn build_summary_basic() {
        let s = build_summary(2, 10, 3, &[]);
        assert_eq!(s, "2 file(s) changed, +10 -3");
    }

    #[test]
    fn build_summary_with_functions() {
        let funcs = vec!["auth.rs:login".to_string()];
        let s = build_summary(1, 5, 2, &funcs);
        assert!(s.contains("login"));
    }

    #[test]
    fn detect_new_symbol() {
        let old = "fn hello() {}\n";
        let new = "fn hello() {}\nfn world() {}\n";
        let mut notes = Vec::new();
        detect_semantic_changes(old, new, Some("rs"), "test.rs", &mut notes);
        assert!(
            notes
                .iter()
                .any(|n| n.contains("new symbol") && n.contains("world")),
            "should detect new symbol: {notes:?}"
        );
    }

    #[test]
    fn detect_removed_symbol() {
        let old = "fn hello() {}\nfn world() {}\n";
        let new = "fn hello() {}\n";
        let mut notes = Vec::new();
        detect_semantic_changes(old, new, Some("rs"), "test.rs", &mut notes);
        assert!(
            notes
                .iter()
                .any(|n| n.contains("removed symbol") && n.contains("world")),
            "should detect removed symbol: {notes:?}"
        );
    }

    #[test]
    fn detect_signature_change() {
        let old = "fn hello(x: i32) {}\n";
        let new = "fn hello(x: i32, y: i32) {}\n";
        let mut notes = Vec::new();
        detect_semantic_changes(old, new, Some("rs"), "test.rs", &mut notes);
        assert!(
            notes.iter().any(|n| n.contains("signature changed")),
            "should detect signature change: {notes:?}"
        );
    }

    #[test]
    fn no_changes_detected() {
        let content = "fn hello() {}\n";
        let mut notes = Vec::new();
        detect_semantic_changes(content, content, Some("rs"), "test.rs", &mut notes);
        assert!(notes.is_empty());
    }

    #[test]
    fn diff_change_serializes() {
        let change = DiffChange {
            change_type: "addition".to_string(),
            old: None,
            new: Some("let x = 1;".to_string()),
        };
        let json = serde_json::to_string(&change).unwrap();
        assert!(json.contains("\"type\":\"addition\""));
    }

    #[test]
    fn stat_only_has_no_hunks() {
        let output = DiffOutput {
            summary: "test".to_string(),
            stats: DiffStats {
                additions: 1,
                deletions: 0,
                files_changed: 1,
                functions_changed: vec![],
            },
            semantic_notes: vec![],
            hunks: None,
        };
        let json = serde_json::to_value(&output).unwrap();
        assert!(json.get("hunks").is_none());
    }
}