pushkin 0.2.0

Schema-first enforcement harness that gates AI coding agents' file writes against project contracts
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
//! Verb-scoped coverage for the `Bash` arm of the read contract — Option C′
//! of the hook-matcher-gap charter (Addendum D, HM-7 … HM-11).
//!
//! A new file rather than edits to `bash_read_gate.rs` or
//! `bash_read_gate_normalization.rs`: both are committed and so read-only
//! under N10.
//!
//! The property under test is the one C shipped without. C asked whether the
//! command *mentions* a gated path; the read contract cares whether the
//! command *hands the agent unbounded content*. Those diverge in both
//! directions, so this suite pins both: verbs that reveal nothing must stop
//! being denied, and readers that reveal a whole file through a directory or
//! a `<rev>:` spelling must start being.
//!
//! Scope is still the charter's. Classification is positional — token zero,
//! and for `git` token one — and nothing here interprets shell grammar, so
//! quoting, `$()`, pipes and heredocs remain accepted evasions by design.

use assert_cmd::Command;
use std::fs;
use std::path::Path;

type TestResult = Result<(), Box<dyn std::error::Error>>;

const MANIFEST: &str = r#"
version = 1
canonical = "json-schema-2020-12"
authoring = "zod"

[[contracts]]
name = "user"
source = "contracts/user.zod.ts"
emit = ["zod"]

[[mappings]]
glob = "app/api/**/*.ts"
contracts = ["user"]
require = "boundary-validation"

[gates]
protected_paths = ["pushkin.toml"]
retrieval_paths = ["crates/**/*.rs"]
retrieval_tool = "mcp__codebase-retrieval__codebase-retrieval"
"#;

const GATED: &str = "crates/pushkin-core/src/pipeline.rs";

/// The literal prefix of the `retrieval_paths` glob — the directory a
/// recursive reader walks to reach every gated file at once.
const GATED_DIR: &str = "crates/";

const RULE: &str = "pushkin.retrieval.raw_read";

fn seed(dir: &Path, manifest: &str) -> TestResult {
    fs::write(dir.join("pushkin.toml"), manifest)?;
    fs::create_dir_all(dir.join("crates/pushkin-core/src"))?;
    fs::write(dir.join(GATED), "// gated\n")?;
    Ok(())
}

fn repo() -> Result<tempfile::TempDir, Box<dyn std::error::Error>> {
    let dir = tempfile::tempdir()?;
    seed(dir.path(), MANIFEST)?;
    Ok(dir)
}

/// `retrieval_paths`/`retrieval_tool` stripped — a repo that never opted in.
fn unopted_repo() -> Result<tempfile::TempDir, Box<dyn std::error::Error>> {
    let dir = tempfile::tempdir()?;
    let manifest = MANIFEST
        .replace(r#"retrieval_paths = ["crates/**/*.rs"]"#, "")
        .replace(
            r#"retrieval_tool = "mcp__codebase-retrieval__codebase-retrieval""#,
            "",
        );
    seed(dir.path(), &manifest)?;
    Ok(dir)
}

/// One `Bash` tool call through the hook, as Claude would send it.
fn bash(dir: &Path, command: &str) -> Result<String, Box<dyn std::error::Error>> {
    let payload = serde_json::json!({
        "session_id": "bash-gate-verbs",
        "tool_name": "Bash",
        "tool_input": { "command": command },
    })
    .to_string();
    let output = Command::cargo_bin("pushkin")?
        .current_dir(dir)
        .write_stdin(payload)
        .args(["hook", "claude"])
        .output()?;
    Ok(format!(
        "{}{}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    ))
}

fn assert_denied(output: &str, why: &str) {
    assert!(output.contains(RULE), "{why}: {output}");
}

fn assert_allowed(output: &str, why: &str) {
    assert!(!output.contains(RULE), "{why}: {output}");
}

// ---------------------------------------------------------------------------
// HM-9 / HM-11 — verbs that reveal nothing must not be denied by a READ rule
// ---------------------------------------------------------------------------

/// Staging is a write, and this charter's non-goal 2 rejects blocking `Bash`
/// writes at `PreToolUse`. C denied it anyway, with prose telling the agent to
/// call the retrieval tool — advice that cannot be acted on when the goal is
/// to stage a file.
#[test]
fn git_add_stages_a_path_and_is_not_a_read() -> TestResult {
    let dir = repo()?;

    let output = bash(dir.path(), &format!("git add {GATED}"))?;

    assert_allowed(&output, "staging reveals no content");
    Ok(())
}

/// Restoring a path overwrites it from the index. Nothing is shown.
#[test]
fn git_checkout_restores_a_path_and_is_not_a_read() -> TestResult {
    let dir = repo()?;

    let output = bash(dir.path(), &format!("git checkout -- {GATED}"))?;

    assert_allowed(&output, "restore reveals no content");
    Ok(())
}

/// The sharpest case: a read gate denying a deletion. Whether `rm` should be
/// gated at all is a different charter's question; it is certainly not a read.
#[test]
fn rm_deletes_without_revealing_and_is_not_a_read() -> TestResult {
    let dir = repo()?;

    let output = bash(dir.path(), &format!("rm {GATED}"))?;

    assert_allowed(&output, "deletion reveals no content");
    Ok(())
}

/// Subject lines and hashes, never file contents.
#[test]
fn git_log_oneline_shows_subjects_not_contents() -> TestResult {
    let dir = repo()?;

    let output = bash(dir.path(), &format!("git log --oneline -- {GATED}"))?;

    assert_allowed(&output, "log metadata reveals no content");
    Ok(())
}

/// A count is the canonical example of a question about a file that is not a
/// read of it.
#[test]
fn wc_counts_lines_without_revealing_them() -> TestResult {
    let dir = repo()?;

    let output = bash(dir.path(), &format!("wc -l {GATED}"))?;

    assert_allowed(&output, "a line count reveals no content");
    Ok(())
}

/// The build surface names paths constantly and must never enter the scan.
#[test]
fn cargo_never_enters_the_scan() -> TestResult {
    let dir = repo()?;

    let output = bash(dir.path(), &format!("cargo build --manifest-path {GATED}"))?;

    assert_allowed(&output, "cargo is not a reader");
    Ok(())
}

// ---------------------------------------------------------------------------
// HM-7 / HM-8 — content-bearing git subcommands must be denied
// ---------------------------------------------------------------------------

/// `blame` prints every line of the file with an annotation attached.
#[test]
fn git_blame_prints_the_file_and_is_denied() -> TestResult {
    let dir = repo()?;

    let output = bash(dir.path(), &format!("git blame {GATED}"))?;

    assert_denied(&output, "blame prints the whole file");
    Ok(())
}

/// `-p` turns a metadata command into a full-content one.
#[test]
fn git_log_with_patch_prints_the_file_and_is_denied() -> TestResult {
    let dir = repo()?;

    let output = bash(dir.path(), &format!("git log -p -- {GATED}"))?;

    assert_denied(&output, "log -p prints the file");
    Ok(())
}

/// HM-7 in its `git` spelling: a directory pathspec reaches every gated file
/// at once, and the token never matches a `*.rs` glob.
#[test]
fn git_grep_searches_gated_content_and_is_denied() -> TestResult {
    let dir = repo()?;

    let output = bash(dir.path(), &format!("git grep 'fn parse' -- {GATED_DIR}"))?;

    assert_denied(&output, "git grep reads every file under the pathspec");
    Ok(())
}

/// HM-8: `<rev>:<path>` prints the whole file and defeats the glob, because
/// normalization strips `./` and the repo root but not a revision prefix.
#[test]
fn git_show_of_a_rev_scoped_path_prints_the_file_and_is_denied() -> TestResult {
    let dir = repo()?;

    let output = bash(dir.path(), &format!("git show HEAD:{GATED}"))?;

    assert_denied(&output, "rev:path is a whole-file read");
    Ok(())
}

/// A diff hands over changed hunks of the file.
#[test]
fn git_diff_of_a_gated_path_is_denied() -> TestResult {
    let dir = repo()?;

    let output = bash(dir.path(), &format!("git diff {GATED}"))?;

    assert_denied(&output, "a diff carries file content");
    Ok(())
}

/// The same subcommand reduced to names is metadata, and is the compliant
/// alternative the deny should leave available.
#[test]
fn git_diff_name_only_is_metadata_and_is_allowed() -> TestResult {
    let dir = repo()?;

    let output = bash(dir.path(), &format!("git diff --name-only {GATED}"))?;

    assert_allowed(&output, "--name-only reveals no content");
    Ok(())
}

/// `--stat` is the same reduction for `show`.
#[test]
fn git_show_with_stat_is_metadata_and_is_allowed() -> TestResult {
    let dir = repo()?;

    let output = bash(dir.path(), &format!("git show --stat HEAD -- {GATED}"))?;

    assert_allowed(&output, "--stat reveals no content");
    Ok(())
}

// ---------------------------------------------------------------------------
// HM-7 — recursive readers reach gated files through a directory
// ---------------------------------------------------------------------------

/// The charter's opening anecdote in its cheaper spelling: the agent never
/// names a `.rs` file, so C's glob never matched and the read sailed through.
#[test]
fn a_recursive_grep_of_a_gated_directory_is_denied() -> TestResult {
    let dir = repo()?;

    let output = bash(dir.path(), &format!("grep -rn 'fn parse' {GATED_DIR}"))?;

    assert_denied(&output, "-r reaches every gated file under the directory");
    Ok(())
}

/// `rg` needs no flag to recurse, so the flag cannot be the discriminator.
#[test]
fn ripgrep_is_recursive_by_default_and_is_denied() -> TestResult {
    let dir = repo()?;

    let output = bash(dir.path(), &format!("rg 'fn parse' {GATED_DIR}"))?;

    assert_denied(&output, "rg recurses without being asked");
    Ok(())
}

/// The discriminator is the verb, not the directory: naming the same
/// directory to a non-reader must stay silent, or C′ has merely moved the
/// overblocking rather than removed it.
#[test]
fn listing_the_same_directory_is_not_a_read() -> TestResult {
    let dir = repo()?;

    let output = bash(dir.path(), &format!("ls -l {GATED_DIR}"))?;

    assert_allowed(&output, "a listing is not a read");
    Ok(())
}

// ---------------------------------------------------------------------------
// HM-10 — the range hatch stays a `Read`-surface allowance, on purpose
// ---------------------------------------------------------------------------
//
// Addendum D left the direction to the human and named two: honor ranges on
// `Bash` too, or narrow the record. The first is unavailable — `head -50` and
// `sed -n '1,80p'` are pinned as denials by the committed
// `bash_read_gate.rs::shell_readers_of_a_gated_path_are_denied`, which is
// read-only under N10 — and it is also the weaker of the two. On `Read` the
// host hands the gate `offset`/`limit` as structured fields it can verify; in
// a command string a bound can only be inferred, and nothing distinguishes
// `head -50` from `head -999999`. The surfaces differ because the guarantee
// differs, so what needed correcting was the record, not the behavior.

/// An apparent range in a command string buys nothing, because the gate
/// cannot verify it. The compliant routes stay the retrieval tool and the
/// `Read` surface, both of which the deny prose already names.
#[test]
fn an_apparent_range_does_not_unlock_a_shell_read() -> TestResult {
    let dir = repo()?;

    let output = bash(dir.path(), &format!("sed -n 1,50p {GATED}"))?;

    assert_denied(&output, "a bound the gate cannot verify is not a bound");
    Ok(())
}

/// The same rule for the reader whose bound is a bare count.
#[test]
fn head_with_a_line_count_is_still_a_shell_read() -> TestResult {
    let dir = repo()?;

    let output = bash(dir.path(), &format!("head -50 {GATED}"))?;

    assert_denied(&output, "`head -999999` reads as bounded as `head -50`");
    Ok(())
}

/// And the unranged spelling, so the denial is not resting on the flag.
#[test]
fn an_unbounded_sed_script_is_denied() -> TestResult {
    let dir = repo()?;

    let output = bash(dir.path(), &format!("sed 's/a/b/' {GATED}"))?;

    assert_denied(&output, "sed streams the whole file");
    Ok(())
}

/// The asymmetry is only defensible if the `Read` surface really does keep
/// its half — this is the control that would catch C′ narrowing that hatch by
/// accident.
#[test]
fn the_read_surface_still_honors_an_explicit_range() -> TestResult {
    let dir = repo()?;
    let payload = serde_json::json!({
        "session_id": "bash-gate-verbs",
        "tool_name": "Read",
        "tool_input": { "file_path": GATED, "offset": 1, "limit": 50 },
    })
    .to_string();

    let output = Command::cargo_bin("pushkin")?
        .current_dir(dir.path())
        .write_stdin(payload)
        .args(["hook", "claude"])
        .output()?;
    let output = format!(
        "{}{}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );

    assert_allowed(&output, "a verifiable range is still the deliberate shape");
    Ok(())
}

// ---------------------------------------------------------------------------
// Regression guard and inertness
// ---------------------------------------------------------------------------

/// What C closed must stay closed.
#[test]
fn cat_of_a_gated_path_is_still_denied() -> TestResult {
    let dir = repo()?;

    let output = bash(dir.path(), &format!("cat {GATED}"))?;

    assert_denied(&output, "the unbounded single-file read is C's whole point");
    Ok(())
}

/// A repo that never opted in sees no verdict from any verb.
#[test]
fn an_unopted_repo_gates_no_verb() -> TestResult {
    let dir = unopted_repo()?;

    for command in [
        format!("cat {GATED}"),
        format!("grep -rn 'x' {GATED_DIR}"),
        format!("git show HEAD:{GATED}"),
    ] {
        let output = bash(dir.path(), &command)?;
        assert_allowed(&output, "an unopted repo gates nothing");
    }
    Ok(())
}