pushkin 0.2.1

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
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
//! F48 Phase A — `Edit`/`MultiEdit` must stop failing open at `PreToolUse`.
//!
//! COMMITTED RED. Every test here asserts Phase A's contract and fails on
//! today's tree, where `Edit` carries `old_string`/`new_string` and
//! `MultiEdit` carries `edits[]`, neither carries `content`, both are
//! classified MALFORMED, and the fail-closed fallback consults only
//! `is_protected` — so everything else falls through to a silent ALLOW.
//!
//! Two shapes (`Edit`, `MultiEdit`) across both surfaces (`pushkin check`
//! reading stdin, and `pushkin hook claude`), plus warm/cold parity per the
//! S1c precedent, because a gate that holds cold and not warm is not a gate.
//!
//! Phase A's contract, in three parts:
//!   1. Edit/MultiEdit are recognized MUTATIONS carrying `file_path` with
//!      content ABSENT — no longer "malformed".
//!   2. Path-decidable rules (`protected_paths`, `read_only_paths`, and the
//!      mapped-contract PATH check) evaluate directly from the payload.
//!   3. Content-requiring rules deny under a DISTINCT rule id, so event logs
//!      and Phase B's exit evidence can separate "content unavailable
//!      (interim conservative)" from a real content violation.
//!
//! Phase B (content synthesis from disk) is out of scope here and this suite
//! must not encode it.

use assert_cmd::Command;
use std::fs;
use std::path::Path;
use std::process::Command as StdCommand;

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]
suppression_comments = "deny"
protected_paths = ["pushkin.toml"]
read_only_paths = ["crates/**/tests/**"]
"#;

/// Committed, so the read-only predicate (glob AND present in HEAD) holds.
const COMMITTED_TEST: &str = "crates/pushkin-cli/tests/committed_suite.rs";
/// Mapped to a contract requiring boundary-validation — content-requiring.
const MAPPED: &str = "app/api/users/route.ts";
/// Neither gated nor mapped.
const UNGATED: &str = "docs/notes.md";

const RULE_READ_ONLY: &str = "pushkin.read_only_path";
const RULE_PROTECTED: &str = "pushkin.protected_path";
const RULE_UNVALIDATED: &str = "contract.boundary.unvalidated_input";

/// The distinct id Phase A introduces. Distinct BY DESIGN: reusing
/// `contract.boundary.unvalidated_input` would make "we could not look" and
/// "we looked and it was wrong" indistinguishable in the event log, and
/// Phase B's exit evidence depends on telling them apart.
const RULE_CONTENT_UNAVAILABLE: &str = "pushkin.content_unavailable";

fn git(dir: &Path, args: &[&str]) -> TestResult {
    let status = StdCommand::new("git")
        .current_dir(dir)
        .args(args)
        .status()?;
    assert!(status.success(), "git {args:?} failed");
    Ok(())
}

fn repo() -> Result<tempfile::TempDir, Box<dyn std::error::Error>> {
    let dir = tempfile::tempdir()?;
    fs::write(dir.path().join("pushkin.toml"), MANIFEST)?;
    fs::create_dir_all(dir.path().join("contracts"))?;
    fs::write(
        dir.path().join("contracts/user.zod.ts"),
        "import { z } from 'zod';\nexport const user = z.object({ id: z.string() });\n",
    )?;
    fs::create_dir_all(dir.path().join("crates/pushkin-cli/tests"))?;
    fs::write(dir.path().join(COMMITTED_TEST), "// committed suite\n")?;
    fs::create_dir_all(dir.path().join("app/api/users"))?;
    fs::write(dir.path().join(MAPPED), "export async function POST() {}\n")?;
    fs::create_dir_all(dir.path().join("docs"))?;
    fs::write(dir.path().join(UNGATED), "notes\n")?;
    git(dir.path(), &["init", "-q", "."])?;
    git(dir.path(), &["add", "-A"])?;
    git(
        dir.path(),
        &[
            "-c",
            "user.name=F48 Suite",
            "-c",
            "user.email=f48@test",
            "commit",
            "-qm",
            "fixture",
        ],
    )?;
    Ok(dir)
}

/// A true `Edit` payload: `old_string`/`new_string`, no `content` field.
fn edit_payload(file_path: &str) -> String {
    serde_json::json!({
        "session_id": "f48-phase-a",
        "tool_name": "Edit",
        "tool_input": {
            "file_path": file_path,
            "old_string": "committed",
            "new_string": "tampered",
        },
    })
    .to_string()
}

/// A true `MultiEdit` payload: `edits[]`, no `content` field.
fn multiedit_payload(file_path: &str) -> String {
    serde_json::json!({
        "session_id": "f48-phase-a",
        "tool_name": "MultiEdit",
        "tool_input": {
            "file_path": file_path,
            "edits": [
                { "old_string": "committed", "new_string": "tampered" },
                { "old_string": "suite", "new_string": "gone" },
            ],
        },
    })
    .to_string()
}

fn write_payload(file_path: &str, content: &str) -> String {
    serde_json::json!({
        "session_id": "f48-phase-a",
        "tool_name": "Write",
        "tool_input": { "file_path": file_path, "content": content },
    })
    .to_string()
}

/// `pushkin check` on stdin — exit 2 denies, exit 0 allows.
fn check(dir: &Path, payload: &str) -> Result<(Option<i32>, String), Box<dyn std::error::Error>> {
    let output = Command::cargo_bin("pushkin")?
        .current_dir(dir)
        .write_stdin(payload.to_owned())
        .arg("check")
        .output()?;
    Ok((
        output.status.code(),
        format!(
            "{}{}",
            String::from_utf8_lossy(&output.stdout),
            String::from_utf8_lossy(&output.stderr)
        ),
    ))
}

/// `pushkin hook claude` — the surface an agent actually hits.
/// `daemon` selects the path: `Some("off")` cold, `Some("auto")` warm.
fn hook(
    dir: &Path,
    payload: &str,
    daemon: Option<&str>,
) -> Result<String, Box<dyn std::error::Error>> {
    let mut cmd = Command::cargo_bin("pushkin")?;
    cmd.current_dir(dir).write_stdin(payload.to_owned());
    if let Some(mode) = daemon {
        cmd.env("PUSHKIN_DAEMON", mode);
    }
    let output = cmd.args(["hook", "claude"]).output()?;
    Ok(format!(
        "{}{}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    ))
}

// ---------------------------------------------------------------------------
// Path-decidable rules must be decided from the payload alone
// ---------------------------------------------------------------------------

/// `read_only_paths` needs no content whatsoever — the predicate is a glob
/// plus presence in HEAD. Skipping it on an Edit is pure loss.
#[test]
fn edit_of_a_committed_read_only_file_is_denied_by_the_check_verb() -> TestResult {
    let dir = repo()?;

    let (code, output) = check(dir.path(), &edit_payload(COMMITTED_TEST))?;

    assert_eq!(
        code,
        Some(2),
        "an Edit is a mutation, not a malformed payload: {output}"
    );
    assert!(
        output.contains(RULE_READ_ONLY),
        "the deny names its rule: {output}"
    );
    Ok(())
}

#[test]
fn multiedit_of_a_committed_read_only_file_is_denied_by_the_check_verb() -> TestResult {
    let dir = repo()?;

    let (code, output) = check(dir.path(), &multiedit_payload(COMMITTED_TEST))?;

    assert_eq!(
        code,
        Some(2),
        "edits[] is the same mutation in another shape: {output}"
    );
    assert!(
        output.contains(RULE_READ_ONLY),
        "the deny names its rule: {output}"
    );
    Ok(())
}

#[test]
fn edit_of_a_committed_read_only_file_is_denied_by_the_hook() -> TestResult {
    let dir = repo()?;

    let output = hook(dir.path(), &edit_payload(COMMITTED_TEST), Some("off"))?;

    assert!(
        output.contains(RULE_READ_ONLY),
        "the hook is the surface agents hit; it must not fail open: {output}"
    );
    assert!(
        !output.contains("failing open"),
        "an Edit is recognized, so nothing may narrate a fail-open: {output}"
    );
    Ok(())
}

#[test]
fn multiedit_of_a_committed_read_only_file_is_denied_by_the_hook() -> TestResult {
    let dir = repo()?;

    let output = hook(dir.path(), &multiedit_payload(COMMITTED_TEST), Some("off"))?;

    assert!(
        output.contains(RULE_READ_ONLY),
        "same rule, same surface: {output}"
    );
    Ok(())
}

// F76 ruling 1C: the "edit verdict is identical warm and cold" test that
// lived here was deleted — an Edit normalizes to `MutateNoContent` and never
// reaches the daemon (`check_or_cold` is Write-only), so the assertion
// compared two runs of the same cold code. The verdict it re-asserted is
// pinned discriminately by `edit_of_a_committed_read_only_file_is_denied_by_
// the_hook` and its siblings above.

// ---------------------------------------------------------------------------
// Content-requiring rules fail CLOSED, under a distinct id
// ---------------------------------------------------------------------------

/// A mapped contract path requires boundary-validation, which genuinely
/// needs the file's content. Phase A does not synthesize it — it refuses.
#[test]
fn an_edit_to_a_mapped_contract_path_denies_under_the_content_unavailable_rule() -> TestResult {
    let dir = repo()?;

    let (code, output) = check(dir.path(), &edit_payload(MAPPED))?;

    assert_eq!(
        code,
        Some(2),
        "content-requiring rules fail CLOSED: {output}"
    );
    assert!(
        output.contains(RULE_CONTENT_UNAVAILABLE),
        "the interim refusal carries its own id: {output}"
    );
    Ok(())
}

/// The deny has to be actionable, or it is just an obstacle.
#[test]
fn the_content_unavailable_deny_names_the_tool_the_rule_and_the_remedy() -> TestResult {
    let dir = repo()?;

    let (_, output) = check(dir.path(), &edit_payload(MAPPED))?;

    assert!(
        output.contains("Edit"),
        "name the tool that was refused: {output}"
    );
    assert!(
        output.contains(RULE_UNVALIDATED),
        "name the rule that could not be evaluated: {output}"
    );
    assert!(
        output.contains("Write"),
        "name the remediation — re-issue as Write with full content: {output}"
    );
    assert!(output.contains("F48"), "cite the finding: {output}");
    Ok(())
}

/// The whole point of a separate id: an event log must distinguish "we could
/// not look" from "we looked and it was wrong", or Phase B cannot produce
/// exit evidence.
#[test]
fn the_content_unavailable_rule_id_is_distinct_from_a_real_content_violation() -> TestResult {
    let dir = repo()?;
    let nonconforming = "export async function POST(req) { const b = await req.json(); }\n";

    let (_, interim) = check(dir.path(), &edit_payload(MAPPED))?;
    let (_, real) = check(dir.path(), &write_payload(MAPPED, nonconforming))?;

    assert!(
        interim.contains(RULE_CONTENT_UNAVAILABLE),
        "interim id: {interim}"
    );
    assert!(
        !interim.contains(RULE_UNVALIDATED) || interim.contains(RULE_CONTENT_UNAVAILABLE),
        "the interim deny must not masquerade as a real content violation: {interim}"
    );
    assert!(
        real.contains(RULE_UNVALIDATED),
        "a Write with real content still produces the real rule: {real}"
    );
    assert!(
        !real.contains(RULE_CONTENT_UNAVAILABLE),
        "content WAS available here; the interim id must not appear: {real}"
    );
    Ok(())
}

/// Waivable, following the sibling contract-rule precedent. The posture
/// forbids SILENT allow, not a sanctioned, recorded exception — unlike
/// `read_only_paths`, which is unwaivable by construction.
#[test]
fn the_content_unavailable_rule_is_waivable() -> TestResult {
    let dir = repo()?;

    let waive = Command::cargo_bin("pushkin")?
        .current_dir(dir.path())
        .env("GIT_AUTHOR_NAME", "F48 Suite")
        .args([
            "waive",
            RULE_CONTENT_UNAVAILABLE,
            "--path",
            "app/api/**/*.ts",
            "--ttl",
            "2h",
            "--reason",
            "F48 phase A suite",
        ])
        .output()?;
    assert!(
        waive.status.success(),
        "the grant must be accepted: {}",
        String::from_utf8_lossy(&waive.stderr)
    );

    let (code, output) = check(dir.path(), &edit_payload(MAPPED))?;
    assert_eq!(
        code,
        Some(0),
        "a loud, recorded waiver clears the interim refusal: {output}"
    );
    Ok(())
}

// ---------------------------------------------------------------------------
// Scope guards — what must NOT change
// ---------------------------------------------------------------------------

/// Protected paths already denied on Edit today (the fallback consults
/// `is_protected`). That must survive the change.
#[test]
fn edit_of_a_protected_path_is_still_denied() -> TestResult {
    let dir = repo()?;

    let (code, output) = check(dir.path(), &edit_payload("pushkin.toml"))?;

    assert_eq!(
        code,
        Some(2),
        "protected paths deny on every tool: {output}"
    );
    assert!(
        output.contains(RULE_PROTECTED),
        "unchanged rule id: {output}"
    );
    Ok(())
}

/// Recognizing Edit must not turn every edit into a deny. An ungated,
/// unmapped path has no rule to evaluate and stays silent.
#[test]
fn an_edit_to_an_ungated_unmapped_path_is_allowed() -> TestResult {
    let dir = repo()?;

    let (code, output) = check(dir.path(), &edit_payload(UNGATED))?;

    assert_eq!(
        code,
        Some(0),
        "no rule applies, so nothing to refuse: {output}"
    );
    assert!(
        !output.contains(RULE_CONTENT_UNAVAILABLE),
        "the interim refusal fires only where a content rule actually maps: {output}"
    );
    Ok(())
}

/// The `Write` path is untouched by all of this.
#[test]
fn a_write_carrying_content_is_unchanged() -> TestResult {
    let dir = repo()?;

    let (code, output) = check(dir.path(), &write_payload(COMMITTED_TEST, "// tampered\n"))?;

    assert_eq!(
        code,
        Some(2),
        "Write to a committed read-only file still denies: {output}"
    );
    assert!(
        output.contains(RULE_READ_ONLY),
        "unchanged rule id: {output}"
    );
    Ok(())
}