git-prism 0.10.0

Agent-optimized git data MCP server — structured change manifests and full file snapshots for LLM 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
#![cfg(unix)]

//! Adversarial QA (issue #343, gate 3): stable shim target derivation.
//!
//! `stable_shim_target` rewrites a Homebrew-Cellar exe path
//! (`<prefix>/Cellar/<formula>/<version>/bin/<bin>`) to the stable
//! `<prefix>/bin/<bin>` so the shim survives `brew upgrade`. These tests drive
//! the REAL binary end-to-end: we copy the built `git-prism` into a synthetic
//! on-disk layout, run `<copy> shim install` with an isolated HOME, and inspect
//! the symlink target it produces. Because `install_path_shim` resolves the
//! target from `std::env::current_exe()`, running a relocated copy is the only
//! black-box way to exercise the Cellar-detection branch.

use std::fs;
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};

use tempfile::TempDir;

const CLEAN_PATH: &str = "/usr/bin:/bin:/usr/sbin:/sbin";

/// Copy the built test binary to `dest`, preserving the exec bit. Creates parent
/// dirs as needed. Returns `dest`.
fn copy_binary_to(dest: &Path) -> PathBuf {
    let src = env!("CARGO_BIN_EXE_git-prism");
    fs::create_dir_all(dest.parent().unwrap()).unwrap();
    fs::copy(src, dest).unwrap();
    let mut perms = fs::metadata(dest).unwrap().permissions();
    perms.set_mode(0o755);
    fs::set_permissions(dest, perms).unwrap();
    dest.to_path_buf()
}

/// Run `<exe> shim install` with an isolated HOME, declining the PATH prompt.
/// Returns the symlink target that was created (read_link of the shim).
fn install_and_read_target(exe: &Path, home: &Path) -> PathBuf {
    let out = Command::new(exe)
        .env("HOME", home)
        .env("PATH", CLEAN_PATH)
        .env("SHELL", "/bin/zsh")
        .args(["shim", "install"])
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .and_then(|mut child| {
            use std::io::Write;
            child.stdin.take().unwrap().write_all(b"n\n").unwrap();
            child.wait_with_output()
        })
        .unwrap();
    assert!(
        out.status.success(),
        "shim install failed: stdout={} stderr={}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr)
    );
    let link = home.join(".local/share/git-prism/bin/git");
    fs::read_link(&link).unwrap()
}

/// PENTEST A1 (the headline attack): a NON-Homebrew install whose path merely
/// contains a directory literally named `Cellar` above the binary — e.g. a
/// project dir, an encrypted-volume mount, a user who named a folder `Cellar`.
/// The derivation latches onto the first `Cellar` component and computes
/// `<before-Cellar>/bin/<bin>`. If that sibling exists (a `bin/` dir next to a
/// `Cellar/` dir is utterly ordinary), the shim is silently retargeted to an
/// UNRELATED binary instead of the one the user actually ran. That breaks the
/// install (`git` shim points at the wrong program) with no warning.
#[test]
fn cellar_dir_in_non_homebrew_path_must_not_retarget_to_unrelated_bin() {
    let root = TempDir::new().unwrap();
    let r = root.path();

    // The actual binary the user runs, nested below a stray `Cellar` dir.
    //   <r>/Cellar/work/git-prism      <- real exe (current_exe())
    let real_exe = copy_binary_to(&r.join("Cellar/work/git-prism"));

    // A DIFFERENT, unrelated program sitting at the computed <prefix>/bin/<bin>.
    //   <r>/bin/git-prism              <- not what the user ran
    let unrelated = r.join("bin/git-prism");
    fs::create_dir_all(unrelated.parent().unwrap()).unwrap();
    fs::write(&unrelated, b"#!/bin/sh\necho WRONG BINARY\n").unwrap();
    fs::set_permissions(&unrelated, fs::Permissions::from_mode(0o755)).unwrap();

    let home = TempDir::new().unwrap();
    let target = install_and_read_target(&real_exe, home.path());

    // Correct behavior: this is not a Homebrew Cellar layout, so the shim must
    // point at the binary the user actually ran, NOT the unrelated <r>/bin one.
    let canon_target = fs::canonicalize(&target).unwrap_or(target.clone());
    let canon_real = fs::canonicalize(&real_exe).unwrap();
    let canon_unrelated = fs::canonicalize(&unrelated).unwrap();

    assert_ne!(
        canon_target,
        canon_unrelated,
        "shim was retargeted to an UNRELATED binary because of a stray `Cellar` \
         directory in a non-Homebrew path; target={}",
        target.display()
    );
    assert_eq!(
        canon_target,
        canon_real,
        "shim must point at the binary the user actually ran; target={}",
        target.display()
    );
}

/// PENTEST A2: the derivation does not validate the Homebrew shape
/// (`Cellar/<formula>/<version>/bin/<bin>`). ANY path with a `Cellar` component
/// and an existing `<before-Cellar>/bin/<bin>` is rewritten — even a degenerate
/// `.../Cellar/git-prism` with zero intervening `<formula>/<version>/bin`
/// segments. A real Cellar exe always has those segments.
#[test]
fn cellar_marker_without_formula_version_bin_shape_must_not_rewrite() {
    let root = TempDir::new().unwrap();
    let r = root.path();

    // Degenerate: Cellar immediately followed by the binary.
    let real_exe = copy_binary_to(&r.join("Cellar/git-prism"));

    // Unrelated <r>/bin/git-prism exists.
    let unrelated = r.join("bin/git-prism");
    fs::create_dir_all(unrelated.parent().unwrap()).unwrap();
    fs::write(&unrelated, b"#!/bin/sh\necho WRONG\n").unwrap();
    fs::set_permissions(&unrelated, fs::Permissions::from_mode(0o755)).unwrap();

    let home = TempDir::new().unwrap();
    let target = install_and_read_target(&real_exe, home.path());

    let canon_target = fs::canonicalize(&target).unwrap_or(target.clone());
    let canon_real = fs::canonicalize(&real_exe).unwrap();
    let canon_unrelated = fs::canonicalize(&unrelated).unwrap();
    assert_ne!(
        canon_target,
        canon_unrelated,
        "a path that does not match Cellar/<formula>/<version>/bin/<bin> was \
         still rewritten to <prefix>/bin/<bin>; target={}",
        target.display()
    );
    assert_eq!(
        canon_target,
        canon_real,
        "degenerate Cellar path must point at the binary the user actually ran; target={}",
        target.display()
    );
}

/// Run `<exe> shim status` with an isolated HOME and capture stdout.
fn run_status(exe: &Path, home: &Path) -> String {
    let out = Command::new(exe)
        .env("HOME", home)
        .env("PATH", CLEAN_PATH)
        .args(["shim", "status"])
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .output()
        .unwrap();
    assert!(out.status.success(), "shim status exited non-zero");
    String::from_utf8_lossy(&out.stdout).into_owned()
}

/// PENTEST B1 (documented-contract probe): the `PathShimStatus::Installed`
/// doc comment claims `staleness_warning` is `Some` when "the target is a
/// dangling symlink chain". Plant a shim that points at a DANGLING Cellar path
/// (the Cellar version was GC'd by `brew upgrade` — the exact scenario the fix
/// targets) and assert `shim status` surfaces the Cellar staleness advisory.
///
/// If this fails, the documented dangling-Cellar branch is unreachable: the
/// code only computes the warning inside `if resolved.exists()`, so a dangling
/// Cellar target reports a generic "broken link" with no hint that re-running
/// `git-prism shim install` (the documented remedy) would fix it.
#[test]
fn dangling_cellar_target_status_must_advise_reinstall() {
    let bin = PathBuf::from(env!("CARGO_BIN_EXE_git-prism"));
    let home = TempDir::new().unwrap();
    let h = home.path();

    // Plant a shim symlink pointing at a Cellar path that does NOT exist
    // (post-`brew upgrade` GC of the old version).
    let shim_dir = h.join(".local/share/git-prism/bin");
    fs::create_dir_all(&shim_dir).unwrap();
    let link = shim_dir.join("git");
    let dangling_cellar = h.join("opt/homebrew/Cellar/git-prism/0.9.0/bin/git-prism");
    std::os::unix::fs::symlink(&dangling_cellar, &link).unwrap();

    let stdout = run_status(&bin, h);

    // The documented remedy for a stale Cellar shim is to re-run
    // `git-prism shim install`. A dangling Cellar chain should point the user
    // at that fix, not just say "broken link". (The bare path echoed in a
    // broken-link reason happens to contain "Cellar" but gives no remedy.)
    assert!(
        stdout.contains("git-prism shim install"),
        "status on a dangling Cellar target must mention `git-prism shim install`; got: {stdout:?}"
    );
    assert!(
        stdout.to_lowercase().contains("brew upgrade"),
        "status on a dangling Cellar target must mention `brew upgrade`; got: {stdout:?}"
    );
    assert!(
        stdout.to_lowercase().contains("broken link"),
        "status on a dangling Cellar target must report as broken link; got: {stdout:?}"
    );
}

/// CONTROL: a genuine Homebrew Cellar layout DOES get rewritten to the stable
/// <prefix>/bin/<bin>. Confirms the feature works for the real case so a fix
/// for A1/A2 cannot simply disable rewriting wholesale.
#[test]
fn genuine_homebrew_cellar_layout_rewrites_to_stable_bin() {
    let root = TempDir::new().unwrap();
    let r = root.path();

    // Real-shaped Cellar exe: <r>/Cellar/git-prism/1.0.0/bin/git-prism
    let cellar_exe = copy_binary_to(&r.join("Cellar/git-prism/1.0.0/bin/git-prism"));

    // Stable <r>/bin/git-prism -> the Cellar exe (Homebrew opt link).
    let stable = r.join("bin/git-prism");
    fs::create_dir_all(stable.parent().unwrap()).unwrap();
    std::os::unix::fs::symlink(&cellar_exe, &stable).unwrap();

    let home = TempDir::new().unwrap();
    let target = install_and_read_target(&cellar_exe, home.path());

    assert_eq!(
        fs::canonicalize(&target).unwrap(),
        fs::canonicalize(&stable).unwrap(),
        "genuine Homebrew Cellar exe should be rewritten to <prefix>/bin/<bin>; \
         target={}",
        target.display()
    );
}

// ---------------------------------------------------------------------------
// RUN 2 — re-attack the positional shape validation (Cellar at n-5, bin at n-2)
// ---------------------------------------------------------------------------

/// RUN2 C1: an extra path segment (`libexec/bin`) between the Cellar
/// `<version>` and the binary. Real layout some formulae use:
/// `<prefix>/Cellar/<formula>/<version>/libexec/bin/<bin>` — here Cellar sits
/// at n-6, NOT n-5, so the strict positional check must NOT treat it as the
/// canonical 4-component shape and must return the path unchanged (it would be
/// wrong to point at `<prefix>/bin/<bin>` when the real exe lives under
/// libexec). Confirms the check is anchored to n-5, not "Cellar somewhere with
/// bin near the end".
#[test]
fn cellar_with_extra_libexec_segment_must_not_rewrite() {
    let root = TempDir::new().unwrap();
    let r = root.path();

    // 5 components after Cellar: formula/version/libexec/bin/<bin>
    let real_exe = copy_binary_to(&r.join("Cellar/git-prism/1.0.0/libexec/bin/git-prism"));

    // Unrelated <r>/bin/git-prism exists (the trap).
    let unrelated = r.join("bin/git-prism");
    fs::create_dir_all(unrelated.parent().unwrap()).unwrap();
    fs::write(&unrelated, b"#!/bin/sh\necho WRONG\n").unwrap();
    fs::set_permissions(&unrelated, fs::Permissions::from_mode(0o755)).unwrap();

    let home = TempDir::new().unwrap();
    let target = install_and_read_target(&real_exe, home.path());

    let canon_target = fs::canonicalize(&target).unwrap_or(target.clone());
    let canon_real = fs::canonicalize(&real_exe).unwrap();
    let canon_unrelated = fs::canonicalize(&unrelated).unwrap();
    assert_ne!(
        canon_target,
        canon_unrelated,
        "a libexec/bin Cellar layout (5 trailing components) was rewritten to \
         <prefix>/bin/<bin>; target={}",
        target.display()
    );
    assert_eq!(
        canon_target,
        canon_real,
        "libexec/bin layout must be left unchanged; target={}",
        target.display()
    );
}

/// RUN2 C2: Cellar IS at n-5, but the second-to-last segment is NOT `bin`
/// (`.../Cellar/<formula>/<version>/sbin/<bin>`). The strict check requires
/// `bin` at n-2, so this must be returned unchanged.
#[test]
fn cellar_at_n_minus_5_but_not_bin_at_n_minus_2_must_not_rewrite() {
    let root = TempDir::new().unwrap();
    let r = root.path();

    // Cellar at n-5, but "sbin" (not "bin") at n-2.
    let real_exe = copy_binary_to(&r.join("Cellar/git-prism/1.0.0/sbin/git-prism"));

    // Trap: <r>/bin/git-prism exists.
    let unrelated = r.join("bin/git-prism");
    fs::create_dir_all(unrelated.parent().unwrap()).unwrap();
    fs::write(&unrelated, b"#!/bin/sh\necho WRONG\n").unwrap();
    fs::set_permissions(&unrelated, fs::Permissions::from_mode(0o755)).unwrap();

    let home = TempDir::new().unwrap();
    let target = install_and_read_target(&real_exe, home.path());

    let canon_target = fs::canonicalize(&target).unwrap_or(target.clone());
    let canon_real = fs::canonicalize(&real_exe).unwrap();
    let canon_unrelated = fs::canonicalize(&unrelated).unwrap();
    assert_ne!(
        canon_target,
        canon_unrelated,
        "a Cellar layout with `sbin` (not `bin`) at n-2 was rewritten; target={}",
        target.display()
    );
    assert_eq!(
        canon_target,
        canon_real,
        "sbin layout must point at the binary the user actually ran; target={}",
        target.display()
    );
}

/// RUN2 C3: filename preservation under rewrite. A genuinely Homebrew-shaped
/// exe with a NON-default binary name (`git-prism2`) must rewrite to
/// `<prefix>/bin/git-prism2`, NOT a hardcoded `git-prism`. Proves the derived
/// stable path uses the exe's own file_name().
#[test]
fn rewrite_preserves_non_default_binary_filename() {
    let root = TempDir::new().unwrap();
    let r = root.path();

    let cellar_exe = copy_binary_to(&r.join("Cellar/git-prism/1.0.0/bin/git-prism2"));

    // Stable <r>/bin/git-prism2 exists (matching filename). Also plant a
    // <r>/bin/git-prism decoy to catch any hardcoded-name behavior.
    let stable = r.join("bin/git-prism2");
    fs::create_dir_all(stable.parent().unwrap()).unwrap();
    std::os::unix::fs::symlink(&cellar_exe, &stable).unwrap();
    let decoy = r.join("bin/git-prism");
    fs::write(&decoy, b"#!/bin/sh\necho DECOY\n").unwrap();
    fs::set_permissions(&decoy, fs::Permissions::from_mode(0o755)).unwrap();

    let home = TempDir::new().unwrap();
    let target = install_and_read_target(&cellar_exe, home.path());

    assert_eq!(
        target.file_name().and_then(|s| s.to_str()),
        Some("git-prism2"),
        "rewritten target must keep the exe's own filename (git-prism2), not a \
         hardcoded name; target={}",
        target.display()
    );
    assert_eq!(
        fs::canonicalize(&target).unwrap(),
        fs::canonicalize(&stable).unwrap(),
        "should rewrite to <prefix>/bin/git-prism2; target={}",
        target.display()
    );
}

/// RUN2 C4: a genuine Homebrew Cellar exe whose `<prefix>/bin/<bin>` does NOT
/// exist must fall back to the canonical Cellar path (no phantom target).
#[test]
fn genuine_cellar_without_stable_bin_falls_back_to_canonical() {
    let root = TempDir::new().unwrap();
    let r = root.path();

    let cellar_exe = copy_binary_to(&r.join("Cellar/git-prism/1.0.0/bin/git-prism"));
    // Intentionally do NOT create <r>/bin/git-prism.

    let home = TempDir::new().unwrap();
    let target = install_and_read_target(&cellar_exe, home.path());

    assert_eq!(
        fs::canonicalize(&target).unwrap(),
        fs::canonicalize(&cellar_exe).unwrap(),
        "missing <prefix>/bin/<bin> must fall back to the canonical Cellar exe; \
         target={}",
        target.display()
    );
}

/// RUN2 C5: a plain cargo-install path (no Cellar component anywhere) is left
/// unchanged even when a sibling `<root>/bin/git-prism` exists.
#[test]
fn cargo_install_path_left_unchanged() {
    let root = TempDir::new().unwrap();
    let r = root.path();

    let cargo_exe = copy_binary_to(&r.join(".cargo/bin/git-prism"));

    let home = TempDir::new().unwrap();
    let target = install_and_read_target(&cargo_exe, home.path());

    assert_eq!(
        fs::canonicalize(&target).unwrap(),
        fs::canonicalize(&cargo_exe).unwrap(),
        "cargo-install path (no Cellar) must be unchanged; target={}",
        target.display()
    );
}

/// RUN2 C6 (dangling control): a dangling NON-Cellar target must NOT get the
/// Cellar reinstall advisory — only genuine Cellar staleness should.
#[test]
fn dangling_non_cellar_target_gets_no_cellar_advisory() {
    let bin = PathBuf::from(env!("CARGO_BIN_EXE_git-prism"));
    let home = TempDir::new().unwrap();
    let h = home.path();

    let shim_dir = h.join(".local/share/git-prism/bin");
    fs::create_dir_all(&shim_dir).unwrap();
    let link = shim_dir.join("git");
    // Dangling target with NO Cellar component.
    let dangling = h.join(".cargo/bin/git-prism");
    std::os::unix::fs::symlink(&dangling, &link).unwrap();

    let stdout = run_status(&bin, h);
    // The Cellar-staleness advisory is only for genuine Homebrew Cellar targets;
    // a dangling non-Cellar path must not trigger it. We check for the
    // Brew-specific phrase — the PATH warning is unrelated and allowed here.
    assert!(
        !stdout.to_lowercase().contains("brew upgrade"),
        "a dangling non-Cellar target must not emit a Homebrew/Cellar advisory; \
         got: {stdout:?}"
    );
    assert!(
        stdout.to_lowercase().contains("broken link"),
        "a dangling non-Cellar target must still report as broken link; got: {stdout:?}"
    );
}