drip-cli 0.1.0

Delta Read Interception Proxy — sends only file diffs to your LLM agent
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
use crate::common::Drip;
use serde_json::{json, Value};
use std::fs;
use std::io::Write;
use std::process::{Command, Stdio};

fn run_post_edit(drip: &Drip, payload: Value) {
    run_post_edit_capture(drip, payload);
}

fn run_post_edit_capture(drip: &Drip, payload: Value) -> String {
    let mut child = Command::new(&drip.bin)
        .args(["hook", "claude-post-edit"])
        .env("DRIP_DATA_DIR", drip.data_dir.path())
        .env("DRIP_SESSION_ID", &drip.session_id)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("spawn post-edit hook");
    child
        .stdin
        .as_mut()
        .unwrap()
        .write_all(payload.to_string().as_bytes())
        .unwrap();
    let o = child.wait_with_output().unwrap();
    assert!(o.status.success());
    String::from_utf8_lossy(&o.stdout).into_owned()
}

#[test]
fn edit_then_read_returns_unchanged() {
    let drip = Drip::new();
    let dir = tempfile::tempdir().unwrap();
    let f = dir.path().join("edited.py");
    let before: String = (0..120)
        .map(|i| format!("print('v1 line {i}')  # payload payload payload\n"))
        .collect();
    fs::write(&f, &before).unwrap();

    // Baseline read.
    let out1 = drip.read_stdout(&f);
    assert!(out1.contains("[DRIP: full read"));

    // Model edits the file (Claude Code's Edit tool would do this).
    let after = before.replace("print('v1 line 42')", "print('v2 line 42')");
    fs::write(&f, &after).unwrap();

    // PostToolUse fires.
    run_post_edit(
        &drip,
        json!({
            "tool_name": "Edit",
            "tool_input": { "file_path": f.to_string_lossy() }
        }),
    );

    // Now the model re-reads. With edit-certificates on (default),
    // DRIP returns a compact `[DRIP: edit verified ...]` cert; the
    // read AFTER that returns "unchanged" because the baseline now
    // matches disk content.
    let out2 = drip.read_stdout(&f);
    assert!(
        out2.contains("[DRIP: edit verified"),
        "expected edit verified certificate, got: {out2}"
    );
    let out3 = drip.read_stdout(&f);
    assert!(
        out3.contains("[DRIP: unchanged"),
        "expected unchanged after cert, got: {out3}"
    );
}

#[test]
fn write_tool_also_refreshes_baseline() {
    let drip = Drip::new();
    let dir = tempfile::tempdir().unwrap();
    let f = dir.path().join("w.txt");
    let before = "old value with enough payload for certificate accounting\n".repeat(80);
    fs::write(&f, &before).unwrap();
    drip.read_stdout(&f);

    let after = before.replacen("old value", "new value", 1);
    fs::write(&f, &after).unwrap();
    run_post_edit(
        &drip,
        json!({
            "tool_name": "Write",
            "tool_input": { "file_path": f.to_string_lossy() }
        }),
    );
    // First read after Write: edit certificate (one-shot).
    let out1 = drip.read_stdout(&f);
    assert!(out1.contains("[DRIP: edit verified"), "got: {out1}");
    // Subsequent identical read: unchanged.
    let out2 = drip.read_stdout(&f);
    assert!(out2.contains("[DRIP: unchanged"), "got: {out2}");
}

#[test]
fn unrelated_tools_dont_touch_baseline() {
    let drip = Drip::new();
    let dir = tempfile::tempdir().unwrap();
    let f = dir.path().join("g.txt");
    // Make the file big enough that a 1-line diff is cheaper than a full
    // re-read; otherwise DRIP correctly falls back to "diff bigger than
    // file" and this test misreads that as a baseline-refresh bug.
    let mut v1 = String::new();
    for i in 0..40 {
        v1.push_str(&format!("filler {i}\n"));
    }
    v1.push_str("hello\n");
    fs::write(&f, &v1).unwrap();
    drip.read_stdout(&f);

    let v2 = v1.replace("hello\n", "hello world\n");
    fs::write(&f, &v2).unwrap();
    run_post_edit(
        &drip,
        json!({
            "tool_name": "Bash",
            "tool_input": { "command": "echo hi" }
        }),
    );
    let out = drip.read_stdout(&f);
    assert!(
        out.contains("[DRIP: delta only"),
        "Bash tool must not refresh baseline; got: {out}"
    );
}

#[test]
fn warns_when_edit_targets_an_elided_function_body() {
    // First read returns a semantic-compressed view of `big_fn`, so
    // the agent never saw its body. The Edit hook must surface a
    // warning via `additionalContext` so the model knows to re-read
    // before reasoning further about the function.
    let drip = Drip::new();
    let dir = tempfile::tempdir().unwrap();
    let f = dir.path().join("elided.py");
    let src = "import os\n\n\
        def big_fn(arg_a, arg_b, arg_c):\n    \
            step_one = arg_a + arg_b\n    \
            step_two = step_one * 2\n    \
            step_three = step_two - arg_c\n    \
            step_four = step_three ** 2\n    \
            step_five = step_four + 1\n    \
            step_six = step_five * 3\n    \
            step_seven = step_six - 7\n    \
            step_eight = step_seven + arg_a\n    \
            return step_eight\n\n\
        def small_fn():\n    return 1\n";
    fs::write(&f, src).unwrap();

    // Force compression even on a sub-1KB fixture.
    let _ = drip
        .cmd()
        .arg("read")
        .arg(&f)
        .env("DRIP_COMPRESS_MIN_BYTES", "0")
        .output()
        .unwrap();

    // Mutate a body line whose text doesn't mention `big_fn` — the
    // hook still has to detect the overlap by locating the edit
    // position inside the elided range.
    let mutated = src.replace(
        "step_one = arg_a + arg_b",
        "step_one = arg_a + arg_b + 9999",
    );
    fs::write(&f, &mutated).unwrap();

    let out = run_post_edit_capture(
        &drip,
        json!({
            "tool_name": "Edit",
            "tool_input": {
                "file_path": f.to_string_lossy(),
                "old_string": "step_one = arg_a + arg_b",
                "new_string": "step_one = arg_a + arg_b + 9999",
            }
        }),
    );
    assert!(
        out.contains("edited elided function(s): big_fn"),
        "expected elided-fn warning, got: {out}"
    );
    assert!(
        out.contains("additionalContext"),
        "warning must be delivered via hookSpecificOutput.additionalContext, got: {out}"
    );
}

#[test]
fn no_warning_when_edited_function_body_was_visible() {
    // `small_fn` has a 1-line body — well below DRIP_COMPRESS_MIN_BODY,
    // so the agent saw it intact. Editing it must NOT trigger the
    // elided-function warning (false-positive guard).
    let drip = Drip::new();
    let dir = tempfile::tempdir().unwrap();
    let f = dir.path().join("partial.py");
    let src = "import os\n\n\
        def big_fn(arg_a, arg_b, arg_c):\n    \
            step_one = arg_a + arg_b\n    \
            step_two = step_one * 2\n    \
            step_three = step_two - arg_c\n    \
            step_four = step_three ** 2\n    \
            step_five = step_four + 1\n    \
            step_six = step_five * 3\n    \
            step_seven = step_six - 7\n    \
            step_eight = step_seven + arg_a\n    \
            return step_eight\n\n\
        def small_fn():\n    return 1\n";
    fs::write(&f, src).unwrap();
    let _ = drip
        .cmd()
        .arg("read")
        .arg(&f)
        .env("DRIP_COMPRESS_MIN_BYTES", "0")
        .output()
        .unwrap();

    let mutated = src.replace("return 1\n", "return 42\n");
    fs::write(&f, &mutated).unwrap();

    let out = run_post_edit_capture(
        &drip,
        json!({
            "tool_name": "Edit",
            "tool_input": {
                "file_path": f.to_string_lossy(),
                "old_string": "return 1",
                "new_string": "return 42",
            }
        }),
    );
    assert!(
        !out.contains("edited elided function"),
        "small_fn was visible, must not warn; got: {out}"
    );
}

#[test]
fn cert_contains_hash_and_changed_ranges() {
    let drip = Drip::new();
    let dir = tempfile::tempdir().unwrap();
    let f = dir.path().join("c.py");
    let v1: String = (0..180)
        .map(|i| format!("line {i} payload payload payload\n"))
        .collect();
    fs::write(&f, &v1).unwrap();
    drip.read_stdout(&f);

    let v2 = v1.replacen("line 10", "line 10 EDITED", 1);
    fs::write(&f, &v2).unwrap();
    run_post_edit(
        &drip,
        json!({
            "tool_name": "Edit",
            "tool_input": {
                "file_path": f.to_string_lossy(),
                "old_string": "line 10",
                "new_string": "line 10 EDITED",
            }
        }),
    );

    let out = drip.read_stdout(&f);
    assert!(out.contains("[DRIP: edit verified"), "got: {out}");
    // Hash should appear (hex prefix). The exact value differs but
    // we know the cert prints a `hash:` token.
    assert!(out.contains("hash:"), "missing hash in cert: {out}");
    // The cert advertises how much of the larger file stayed untouched.
    assert!(
        out.contains("Unchanged regions:"),
        "missing unchanged-region tally: {out}"
    );
    // Refresh hint must point users back to the full content.
    assert!(out.contains("drip refresh"), "missing refresh hint: {out}");
}

#[test]
fn cert_disabled_falls_back_to_passthrough() {
    let drip = Drip::new();
    let dir = tempfile::tempdir().unwrap();
    let f = dir.path().join("d.py");
    fs::write(&f, "v1\n").unwrap();
    drip.read_stdout(&f);
    fs::write(&f, "v2\n").unwrap();
    run_post_edit(
        &drip,
        json!({
            "tool_name": "Edit",
            "tool_input": { "file_path": f.to_string_lossy() }
        }),
    );

    // Override env at the read invocation only — the test harness
    // already sets DRIP_DATA_DIR + DRIP_SESSION_ID; we add the disable.
    let mut cmd = drip.cmd();
    cmd.env("DRIP_CERT_DISABLE", "1");
    cmd.arg("read").arg(&f);
    let o = cmd.output().expect("read");
    let out = String::from_utf8_lossy(&o.stdout).into_owned();
    assert!(
        out.contains("[DRIP: post-edit passthrough"),
        "expected legacy passthrough when cert disabled, got: {out}"
    );
}

#[test]
fn cert_is_one_shot_then_unchanged() {
    let drip = Drip::new();
    let dir = tempfile::tempdir().unwrap();
    let f = dir.path().join("e.py");
    let before = "v1 payload payload payload payload\n".repeat(100);
    fs::write(&f, &before).unwrap();
    drip.read_stdout(&f);
    let after = before.replacen("v1", "v2", 1);
    fs::write(&f, &after).unwrap();
    run_post_edit(
        &drip,
        json!({
            "tool_name": "Edit",
            "tool_input": { "file_path": f.to_string_lossy() }
        }),
    );
    let cert = drip.read_stdout(&f);
    assert!(cert.contains("[DRIP: edit verified"), "got: {cert}");
    // Second read on the same content returns unchanged, NOT a cert.
    let next = drip.read_stdout(&f);
    assert!(next.contains("[DRIP: unchanged"), "got: {next}");
    // Third read same as second.
    let next2 = drip.read_stdout(&f);
    assert!(next2.contains("[DRIP: unchanged"), "got: {next2}");
}

#[test]
fn cert_requires_existing_baseline() {
    // PostToolUse fires for a file DRIP has never seen — no baseline
    // means no diff to certify, fall back to passthrough.
    let drip = Drip::new();
    let dir = tempfile::tempdir().unwrap();
    let f = dir.path().join("u.py");
    fs::write(&f, "fresh\n").unwrap();
    run_post_edit(
        &drip,
        json!({
            "tool_name": "Write",
            "tool_input": { "file_path": f.to_string_lossy() }
        }),
    );
    let out = drip.read_stdout(&f);
    assert!(
        out.contains("[DRIP: post-edit passthrough"),
        "expected passthrough on no-baseline edit, got: {out}"
    );
}

#[test]
fn post_edit_does_not_persist_dripignored_secrets() {
    // Privacy regression: an Edit on a `.env` file used to land its
    // contents in the per-session `reads` table AND the cross-
    // session `file_registry`, where backup tools could carry it
    // off-host. The Read path explicitly substitutes a placeholder
    // for dripignore'd files; the post-edit path now applies the
    // same gate before calling `set_baseline`.
    let drip = Drip::new();
    let dir = tempfile::tempdir().unwrap();
    let env_file = dir.path().join(".env");
    let secret = "DATABASE_URL=postgres://user:s3cr3t@db/prod\n";
    fs::write(&env_file, secret).unwrap();

    run_post_edit(
        &drip,
        json!({
            "tool_name": "Edit",
            "tool_input": { "file_path": env_file.to_string_lossy() }
        }),
    );

    // Read the SQLite store directly to confirm the secret never
    // reached either storage table. The DB lives at
    // `<DRIP_DATA_DIR>/sessions.db`.
    let db_path = drip.data_dir.path().join("sessions.db");
    if db_path.exists() {
        let db_bytes = std::fs::read(&db_path).unwrap();
        let needle = "s3cr3t";
        assert!(
            !db_bytes
                .windows(needle.len())
                .any(|w| w == needle.as_bytes()),
            ".env contents leaked into sessions.db — post-edit hook should honour .dripignore"
        );
    }

    // Also check the file-cache directory: large blobs spill there.
    let cache_dir = drip.data_dir.path().join("cache");
    if cache_dir.exists() {
        for entry in std::fs::read_dir(&cache_dir).unwrap().flatten() {
            let body = std::fs::read_to_string(entry.path()).unwrap_or_default();
            assert!(
                !body.contains("s3cr3t"),
                ".env contents leaked into cache/{}",
                entry.file_name().to_string_lossy()
            );
        }
    }
}