entropyx-cli 0.1.0

CLI front-end for entropyx.
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
//! End-to-end: compiled `entropyx explain <repo> <file>` filters the
//! walk to the requested file and emits per-file evidence + commit list.

use std::fs;
use std::path::Path;
use std::process::Command;
use tempfile::tempdir;

/// Build a Command rooted at the test binary with ENTROPYX_CACHE_DIR
/// pointing inside `td_path`, so each test gets isolated disk caches.
fn cli_cmd(td_path: &Path) -> Command {
    let mut cmd = Command::new(env!("CARGO_BIN_EXE_entropyx"));
    cmd.env("ENTROPYX_CACHE_DIR", td_path);
    cmd
}

fn run_git(cwd: &Path, args: &[&str]) {
    let status = Command::new("git")
        .args(args)
        .current_dir(cwd)
        .status()
        .expect("spawn git");
    assert!(status.success(), "git {args:?} failed");
}

fn commit_as(cwd: &Path, name: &str, email: &str, time: i64, subject: &str) {
    run_git(cwd, &["add", "-A"]);
    let status = Command::new("git")
        .args([
            "-c",
            &format!("user.name={name}"),
            "-c",
            &format!("user.email={email}"),
            "commit",
            "-q",
            "-m",
            subject,
        ])
        .env("GIT_AUTHOR_DATE", format!("@{time} +0000"))
        .env("GIT_COMMITTER_DATE", format!("@{time} +0000"))
        .current_dir(cwd)
        .status()
        .expect("spawn git");
    assert!(status.success(), "git commit {subject} failed");
}

#[test]
fn explain_filters_to_single_file() {
    let td = tempdir().expect("tempdir");
    let root = td.path();
    run_git(root, &["init", "--quiet"]);

    // 3 commits: a.rs touched in c1+c2; b.rs touched in c2+c3.
    fs::write(root.join("a.rs"), "one\n").unwrap();
    commit_as(root, "Alice", "alice@ex.com", 100, "add a");

    fs::write(root.join("a.rs"), "one\ntwo\n").unwrap();
    fs::write(root.join("b.rs"), "bb\n").unwrap();
    commit_as(root, "Bob", "bob@ex.com", 200, "touch a, add b");

    fs::write(root.join("b.rs"), "bb\ncc\n").unwrap();
    commit_as(root, "Alice", "alice@ex.com", 400, "touch b");

    let out = cli_cmd(td.path())
        .args(["explain"])
        .arg(root)
        .arg("a.rs")
        .output()
        .expect("spawn entropyx");
    assert!(
        out.status.success(),
        "explain failed: stderr={}",
        String::from_utf8_lossy(&out.stderr),
    );

    let report: serde_json::Value = serde_json::from_slice(&out.stdout).expect("stdout is JSON");

    assert_eq!(report["schema"]["name"], "entropyx-explain");
    assert_eq!(report["path"], "a.rs");
    assert_eq!(report["commits_touched"], 2);
    assert_eq!(report["first_commit_time"], 100);
    assert_eq!(report["last_commit_time"], 200);

    // Two commits, two distinct authors at 50% each.
    let tops = report["top_authors"].as_array().unwrap();
    assert_eq!(tops.len(), 2);
    for t in tops {
        assert!((t["share"].as_f64().unwrap() - 0.5).abs() < 1e-12);
    }

    // Commits list is newest-first (walk order), only the ones touching a.rs.
    let commits = report["commits"].as_array().unwrap();
    assert_eq!(commits.len(), 2);
    assert_eq!(commits[0]["subject"], "touch a, add b");
    assert_eq!(commits[0]["author"], "bob@ex.com");
    assert_eq!(commits[1]["subject"], "add a");
    assert_eq!(commits[1]["author"], "alice@ex.com");

    // Per-file metrics: 2 authors uniform → dispersion=1.0; 1 gap → V_t=0.
    let m = &report["metrics"];
    assert_eq!(m["change_count"], 2);
    assert!((m["author_dispersion"].as_f64().unwrap() - 1.0).abs() < 1e-12);
    assert_eq!(m["temporal_volatility"], 0.0);
}

#[test]
fn explain_unknown_path_yields_empty_evidence() {
    let td = tempdir().expect("tempdir");
    let root = td.path();
    run_git(root, &["init", "--quiet"]);
    fs::write(root.join("a.rs"), "one\n").unwrap();
    commit_as(root, "Alice", "alice@ex.com", 100, "add a");

    let out = cli_cmd(td.path())
        .args(["explain"])
        .arg(root)
        .arg("does/not/exist.rs")
        .output()
        .expect("spawn entropyx");
    assert!(out.status.success(), "unknown path is a valid empty query");

    let report: serde_json::Value = serde_json::from_slice(&out.stdout).expect("stdout is JSON");
    assert_eq!(report["commits_touched"], 0);
    assert!(report["commits"].as_array().unwrap().is_empty());
    assert!(report["top_authors"].as_array().unwrap().is_empty());
    assert!(report["first_commit_time"].is_null());
}

#[test]
fn explain_resolves_handle_key() {
    // Round-trip: `scan` mints a file:<prefix> key; feeding that key back
    // to `explain` must resolve to the same path and produce the same
    // per-file evidence as calling with the raw path.
    let td = tempdir().expect("tempdir");
    let root = td.path();
    run_git(root, &["init", "--quiet"]);

    fs::write(root.join("target.rs"), "v1\n").unwrap();
    commit_as(root, "Alice", "alice@ex.com", 100, "add target");
    fs::write(root.join("target.rs"), "v1\nv2\n").unwrap();
    commit_as(root, "Bob", "bob@ex.com", 200, "touch target");

    // Step 1: scan emits a Summary; grab the handle key.
    let scan_out = cli_cmd(td.path())
        .args(["scan"])
        .arg(root)
        .output()
        .expect("scan");
    assert!(scan_out.status.success());
    let summary: serde_json::Value = serde_json::from_slice(&scan_out.stdout).unwrap();
    let handles = summary["handles"].as_object().unwrap();
    assert_eq!(handles.len(), 1);
    let handle_key = handles.keys().next().unwrap().clone();
    assert!(handle_key.starts_with("file:"));

    // Step 2: explain with the handle key.
    let explain_by_handle = cli_cmd(td.path())
        .args(["explain"])
        .arg(root)
        .arg(&handle_key)
        .output()
        .expect("explain");
    assert!(
        explain_by_handle.status.success(),
        "explain via handle: stderr={}",
        String::from_utf8_lossy(&explain_by_handle.stderr),
    );
    let by_handle: serde_json::Value = serde_json::from_slice(&explain_by_handle.stdout).unwrap();
    assert_eq!(by_handle["path"], "target.rs");
    assert_eq!(by_handle["commits_touched"], 2);

    // Step 3: explain with the raw path — should match exactly.
    let explain_by_path = cli_cmd(td.path())
        .args(["explain"])
        .arg(root)
        .arg("target.rs")
        .output()
        .expect("explain");
    assert!(explain_by_path.status.success());
    let by_path: serde_json::Value = serde_json::from_slice(&explain_by_path.stdout).unwrap();
    assert_eq!(
        by_handle, by_path,
        "handle and path must yield identical evidence"
    );
}

#[test]
fn explain_unknown_handle_fails_cleanly() {
    let td = tempdir().expect("tempdir");
    let root = td.path();
    run_git(root, &["init", "--quiet"]);
    fs::write(root.join("a.rs"), "x\n").unwrap();
    commit_as(root, "Alice", "alice@ex.com", 100, "add a");

    let out = cli_cmd(td.path())
        .args(["explain"])
        .arg(root)
        .arg("file:deadbeefcafe")
        .output()
        .expect("spawn");
    assert!(!out.status.success());
    assert!(
        String::from_utf8_lossy(&out.stderr).contains("matches no blob at HEAD"),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr),
    );
}

fn rev_parse_head(cwd: &Path) -> String {
    let out = Command::new("git")
        .args(["rev-parse", "HEAD"])
        .current_dir(cwd)
        .output()
        .expect("rev-parse");
    String::from_utf8(out.stdout).unwrap().trim().to_string()
}

#[test]
fn explain_commit_handle_returns_meta_and_changes() {
    let td = tempdir().expect("tempdir");
    let root = td.path();
    run_git(root, &["init", "--quiet"]);

    fs::write(root.join("a.rs"), "v1\n").unwrap();
    commit_as(root, "Alice", "alice@ex.com", 100, "add a");
    fs::write(root.join("a.rs"), "v1\nv2\n").unwrap();
    fs::write(root.join("b.rs"), "bb\n").unwrap();
    commit_as(root, "Bob", "bob@ex.com", 200, "touch a, add b");

    let sha = rev_parse_head(root);
    assert_eq!(sha.len(), 40);

    let out = cli_cmd(td.path())
        .args(["explain"])
        .arg(root)
        .arg(format!("commit:{sha}"))
        .output()
        .expect("spawn");
    assert!(
        out.status.success(),
        "commit explain failed: stderr={}",
        String::from_utf8_lossy(&out.stderr),
    );

    let r: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap();
    assert_eq!(r["kind"], "commit");
    assert_eq!(r["commit"]["sha"], sha);
    assert_eq!(r["commit"]["subject"], "touch a, add b");
    assert_eq!(r["commit"]["author"]["email"], "bob@ex.com");
    assert_eq!(r["commit"]["committer"]["time"], 200);
    assert_eq!(r["commit"]["parents"].as_array().unwrap().len(), 1);

    let changes = r["changes"].as_array().unwrap();
    assert_eq!(changes.len(), 2);
    let paths: Vec<&str> = changes
        .iter()
        .map(|c| c["path"].as_str().unwrap())
        .collect();
    assert!(paths.contains(&"a.rs"));
    assert!(paths.contains(&"b.rs"));
    assert_eq!(r["stats"]["files_changed"], 2);
    assert_eq!(r["stats"]["renames"], 0);
}

#[test]
fn explain_commit_unknown_sha_fails_cleanly() {
    let td = tempdir().expect("tempdir");
    let root = td.path();
    run_git(root, &["init", "--quiet"]);
    fs::write(root.join("a.rs"), "x\n").unwrap();
    commit_as(root, "Alice", "alice@ex.com", 100, "add");

    let out = cli_cmd(td.path())
        .args(["explain"])
        .arg(root)
        .arg("commit:0000000000000000000000000000000000000000")
        .output()
        .expect("spawn");
    assert!(!out.status.success());
    assert!(
        String::from_utf8_lossy(&out.stderr).contains("not found"),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr),
    );
}

#[test]
fn explain_range_handle_excludes_base() {
    // 3 linear commits: c1 → c2 → c3. `range:c1..c3` should yield
    // {c2, c3} — the canonical git log base..head set.
    let td = tempdir().expect("tempdir");
    let root = td.path();
    run_git(root, &["init", "--quiet"]);

    fs::write(root.join("f.rs"), "v1\n").unwrap();
    commit_as(root, "A", "a@ex.com", 100, "c1");
    let c1 = rev_parse_head(root);

    fs::write(root.join("f.rs"), "v1\nv2\n").unwrap();
    commit_as(root, "B", "b@ex.com", 200, "c2");

    fs::write(root.join("f.rs"), "v1\nv2\nv3\n").unwrap();
    commit_as(root, "A", "a@ex.com", 300, "c3");
    let c3 = rev_parse_head(root);

    let out = cli_cmd(td.path())
        .args(["explain"])
        .arg(root)
        .arg(format!("range:{c1}..{c3}"))
        .output()
        .expect("spawn");
    assert!(
        out.status.success(),
        "range explain failed: stderr={}",
        String::from_utf8_lossy(&out.stderr),
    );

    let r: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap();
    assert_eq!(r["kind"], "range");
    assert_eq!(r["range"]["base"], c1);
    assert_eq!(r["range"]["head"], c3);
    assert_eq!(r["commit_count"], 2, "base is excluded");
    assert_eq!(r["distinct_authors"], 2);
    assert_eq!(r["first_commit_time"], 200);
    assert_eq!(r["last_commit_time"], 300);
    // The single file was touched in both c2 and c3, so exactly one entry.
    let files: Vec<&str> = r["files_touched"]
        .as_array()
        .unwrap()
        .iter()
        .map(|v| v.as_str().unwrap())
        .collect();
    assert_eq!(files, vec!["f.rs"]);

    // Commits list is newest-first (matches walk order).
    let commits = r["commits"].as_array().unwrap();
    assert_eq!(commits.len(), 2);
    assert_eq!(commits[0]["subject"], "c3");
    assert_eq!(commits[1]["subject"], "c2");
}

#[test]
fn explain_commit_without_github_flag_has_no_pr_field() {
    // Regression guard: adding --github is strictly additive. When the
    // flag is absent the commit explain output must not contain
    // "pull_request" at all (not even null).
    let td = tempdir().expect("tempdir");
    let root = td.path();
    run_git(root, &["init", "--quiet"]);
    fs::write(root.join("a.rs"), "v1\n").unwrap();
    commit_as(root, "Alice", "alice@ex.com", 100, "init");
    let sha = rev_parse_head(root);

    let out = cli_cmd(td.path())
        .args(["explain"])
        .arg(root)
        .arg(format!("commit:{sha}"))
        .output()
        .expect("spawn");
    assert!(out.status.success());
    let r: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap();
    assert!(r.get("pull_request").is_none(), "no flag → no field");
}

#[test]
fn explain_rejects_malformed_github_slug() {
    // With --github present the slug must contain exactly one '/'.
    let td = tempdir().expect("tempdir");
    let root = td.path();
    run_git(root, &["init", "--quiet"]);
    fs::write(root.join("a.rs"), "v1\n").unwrap();
    commit_as(root, "Alice", "alice@ex.com", 100, "init");
    let sha = rev_parse_head(root);

    let out = cli_cmd(td.path())
        .args(["explain"])
        .arg(root)
        .arg(format!("commit:{sha}"))
        .arg("--github")
        .arg("not-a-valid-slug")
        .output()
        .expect("spawn");
    assert!(!out.status.success());
    assert!(
        String::from_utf8_lossy(&out.stderr).contains("owner/name"),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr),
    );
}

#[test]
fn explain_range_malformed_fails_cleanly() {
    let td = tempdir().expect("tempdir");
    let root = td.path();
    run_git(root, &["init", "--quiet"]);
    fs::write(root.join("a.rs"), "x\n").unwrap();
    commit_as(root, "Alice", "alice@ex.com", 100, "add");

    let out = cli_cmd(td.path())
        .args(["explain"])
        .arg(root)
        .arg("range:deadbeef") // missing ".."
        .output()
        .expect("spawn");
    assert!(!out.status.success());
    assert!(
        String::from_utf8_lossy(&out.stderr).contains("malformed range"),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr),
    );
}

#[test]
fn explain_follows_renames() {
    // A commit that renames a.rs -> c.rs should count as a "touch" for
    // BOTH paths (a.rs disappears; c.rs appears). The AI can ask about
    // either side of the rename and get the rewrite in its evidence.
    let td = tempdir().expect("tempdir");
    let root = td.path();
    run_git(root, &["init", "--quiet"]);

    fs::write(root.join("a.rs"), "original\n").unwrap();
    commit_as(root, "Alice", "alice@ex.com", 100, "add a");

    // Rename a.rs -> c.rs with no content change.
    fs::rename(root.join("a.rs"), root.join("c.rs")).unwrap();
    commit_as(root, "Alice", "alice@ex.com", 200, "rename a -> c");

    // Ask about the old path — should see 2 touches (add + rename-away).
    let out_old = cli_cmd(td.path())
        .args(["explain"])
        .arg(root)
        .arg("a.rs")
        .output()
        .expect("spawn");
    assert!(out_old.status.success());
    let r_old: serde_json::Value = serde_json::from_slice(&out_old.stdout).unwrap();
    assert_eq!(r_old["commits_touched"], 2, "a.rs: add + rename-away");

    // Ask about the new path — should see 1 touch (rename-to).
    let out_new = cli_cmd(td.path())
        .args(["explain"])
        .arg(root)
        .arg("c.rs")
        .output()
        .expect("spawn");
    assert!(out_new.status.success());
    let r_new: serde_json::Value = serde_json::from_slice(&out_new.stdout).unwrap();
    assert_eq!(r_new["commits_touched"], 1, "c.rs: rename-to only");
}