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
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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
//! F52 Phase B — the codex arm. The gate judges the file an `apply_patch`
//! Update hunk WILL produce, instead of refusing because a hunk is not a file.
//!
//! COMMITTED RED. A NEW file per N10.
//!
//! **Why this arm is the hardest of the five, and why it still reduces to a
//! replacement.** A codex hunk carries no line numbers — unlike a unified diff's
//! `@@ -a,b +c,d @@`, codex locates a hunk by its CONTEXT. Read that way the
//! hunk is already a replacement in disguise: the lines it expects to find (` `
//! context plus `-` deletions, in order) are the target, and the lines it leaves
//! behind (` ` context plus `+` additions, in order) are the replacement. So the
//! arm builds those two blocks and hands them to the same `apply_edits` every
//! other arm uses. Multiple hunks are multiple replacements, applied in order.
//!
//! **What the `@@` header is, and is not.** `@@ def greet():` names an enclosing
//! scope to disambiguate — it is a LOCATOR HINT, not text adjacent to the hunk.
//! Matching it literally would break every hunk that carries one. It is
//! therefore dropped, and a hunk left ambiguous without it REFUSES rather than
//! picking an occurrence. That is a deliberate over-refusal: codex would have
//! resolved some of those patches through the header we discard.
//!
//! **`*** Move to:` refuses synthesis, deliberately.** A rename means the
//! synthesized content lands at the DESTINATION while the source ceases to
//! exist. Judging the right bytes against the wrong path's rules is a false
//! verdict of the F51 kind, and modelling a rename properly is a delete plus a
//! create — more than this arm is scoped to. The path rules from F58 still
//! apply to both ends; only the CONTENT judgement is withheld.

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/**"]
"#;

const MAPPED: &str = "app/api/users/route.ts";
const COMMITTED_TEST: &str = "crates/pushkin-cli/tests/committed_suite.rs";
const ORDINARY: &str = "docs/notes.md";
/// A MAPPED file carrying a repeated line — ambiguity can only be asserted on
/// a path whose mapping declares a content requirement, since
/// `content_unavailable` fires nowhere else.
const DUPES: &str = "app/api/dupes/route.ts";

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

/// On disk, conforming. Every hunk below is written against these exact lines:
///
///     1 import { UserCreateSchema } from "contracts/user.zod";
///     2 export async function POST(req: Request) {
///     3   const body = UserCreateSchema.parse(await req.json());
///     4   return Response.json(body);
///     5 }
const CONFORMING: &str = "import { UserCreateSchema } from \"contracts/user.zod\";\n\
                          export async function POST(req: Request) {\n  \
                          const body = UserCreateSchema.parse(await req.json());\n  \
                          return Response.json(body);\n}\n";

/// Drops the contract parse. Context lines carry the format's leading space ON
/// TOP of the file's own indentation, so line 4 appears with three spaces.
const BREAK_HUNK: &str = "@@\n\
                          \x20export async function POST(req: Request) {\n\
                          -  const body = UserCreateSchema.parse(await req.json());\n\
                          +  const body = await req.json();\n\
                          \x20  return Response.json(body);\n";

/// Same edit, reached through the scope-naming header form.
const BREAK_HUNK_WITH_HEADER: &str = "@@ export async function POST(req: Request) {\n\
                                      -  const body = UserCreateSchema.parse(await req.json());\n\
                                      +  const body = await req.json();\n\
                                      \x20  return Response.json(body);\n";

/// Leaves the parse in place.
const BENIGN_HUNK: &str = "@@\n\
                           -  return Response.json(body);\n\
                           +  return Response.json({ ...body });\n\
                           \x20}\n";

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"),
        "export const user = 1;\n",
    )?;
    fs::create_dir_all(dir.path().join("app/api/users"))?;
    fs::write(dir.path().join(MAPPED), CONFORMING)?;
    fs::create_dir_all(dir.path().join("app/api/dupes"))?;
    fs::write(
        dir.path().join(DUPES),
        "import { UserCreateSchema } from \"contracts/user.zod\";\n\
         export async function POST(req: Request) {\n  \
         const body = UserCreateSchema.parse(await req.json());\n  \
         log();\n  \
         log();\n  \
         return Response.json(body);\n}\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("docs"))?;
    fs::write(dir.path().join(ORDINARY), "one\ntwo\none\n")?;
    git(dir.path(), &["init", "-q", "."])?;
    git(dir.path(), &["add", "-A"])?;
    git(
        dir.path(),
        &[
            "-c",
            "user.name=F52 Suite",
            "-c",
            "user.email=f52@test",
            "commit",
            "-qm",
            "fixture",
        ],
    )?;
    Ok(dir)
}

fn patch_payload(body: &str) -> String {
    serde_json::json!({
        "session_id": "f52",
        "hook_event_name": "PreToolUse",
        "tool_name": "apply_patch",
        "tool_input": { "command": format!("*** Begin Patch\n{body}*** End Patch\n") },
    })
    .to_string()
}

fn update(path: &str, hunks: &str) -> String {
    patch_payload(&format!("*** Update File: {path}\n{hunks}"))
}

/// Codex also accepts the recorded whole-content shape, which is the natural
/// comparison for the equivalence assertion.
fn write_payload(path: &str, content: &str) -> String {
    serde_json::json!({
        "session_id": "f52",
        "hook_event_name": "PreToolUse",
        "tool_name": "write",
        "tool_input": { "file_path": path, "content": content },
    })
    .to_string()
}

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", "codex"]).output()?;
    Ok(format!(
        "{}{}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    ))
}

fn stop_daemon(dir: &Path) {
    let _ = Command::cargo_bin("pushkin")
        .map(|mut c| c.current_dir(dir).args(["daemon", "stop"]).output());
}

// ---------------------------------------------------------------------------
// The point of the arm
// ---------------------------------------------------------------------------

/// F52 left this refusing. The hunk removes the contract parse, and the gate
/// must now see the VIOLATION rather than the interim placeholder.
#[test]
fn a_hunk_that_breaks_the_contract_is_denied_under_the_real_rule() -> TestResult {
    let dir = repo()?;

    let output = hook(dir.path(), &update(MAPPED, BREAK_HUNK), Some("off"))?;

    assert!(
        output.contains(RULE_UNVALIDATED),
        "the reconstructed file drops the parse and must be judged on it: {output}"
    );
    assert!(
        !output.contains(RULE_CONTENT_UNAVAILABLE),
        "content IS available now — it was reconstructed from the hunk: {output}"
    );
    Ok(())
}

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

    let output = hook(dir.path(), &update(MAPPED, BENIGN_HUNK), Some("off"))?;

    assert!(
        !output.contains(RULE_UNVALIDATED) && !output.contains(RULE_CONTENT_UNAVAILABLE),
        "the reconstructed file still parses through the contract: {output}"
    );
    Ok(())
}

/// The equivalence that defines the program: a hunk producing content X reaches
/// the same verdict as a write of X.
#[test]
fn a_hunk_and_the_equivalent_write_reach_the_same_verdict() -> TestResult {
    let dir = repo()?;
    let reconstructed = CONFORMING.replace(
        "  const body = UserCreateSchema.parse(await req.json());",
        "  const body = await req.json();",
    );

    let via_hunk = hook(dir.path(), &update(MAPPED, BREAK_HUNK), Some("off"))?;
    let via_write = hook(
        dir.path(),
        &write_payload(MAPPED, &reconstructed),
        Some("off"),
    )?;

    for output in [&via_hunk, &via_write] {
        assert!(
            output.contains(RULE_UNVALIDATED),
            "both routes judge the same bytes: {output}"
        );
        // The Phase A refusal NAMES the rule it could not evaluate, so the
        // assertion above matches its prose too. Without this the test passes
        // against a gate that refused both — two refusals, not equivalence.
        assert!(
            !output.contains(RULE_CONTENT_UNAVAILABLE),
            "and judge them, rather than both refusing: {output}"
        );
    }
    Ok(())
}

/// Several hunks in one file apply in order, and the verdict reflects the
/// CUMULATIVE result — here the second hunk repairs what the first broke.
#[test]
fn multiple_hunks_are_judged_on_the_cumulative_result() -> TestResult {
    let dir = repo()?;
    let repair = "@@\n\
                  -  const body = await req.json();\n\
                  +  const body = UserCreateSchema.parse(await req.json());\n\
                  \x20  return Response.json(body);\n";

    let output = hook(
        dir.path(),
        &update(MAPPED, &format!("{BREAK_HUNK}{repair}")),
        Some("off"),
    )?;

    assert!(
        !output.contains(RULE_UNVALIDATED),
        "the second hunk restored the parse; the end state conforms: {output}"
    );
    Ok(())
}

/// The `@@` header names an enclosing scope to disambiguate. It is a LOCATOR
/// HINT, not text adjacent to the hunk — matching it literally would break
/// every hunk that carries one.
#[test]
fn a_scope_header_on_the_at_signs_is_not_matched_literally() -> TestResult {
    let dir = repo()?;

    let output = hook(
        dir.path(),
        &update(MAPPED, BREAK_HUNK_WITH_HEADER),
        Some("off"),
    )?;

    assert!(
        output.contains(RULE_UNVALIDATED),
        "the header locates, it does not participate in the match: {output}"
    );
    assert!(!output.contains(RULE_CONTENT_UNAVAILABLE), "{output}");
    Ok(())
}

// ---------------------------------------------------------------------------
// Where reconstruction stops
// ---------------------------------------------------------------------------

#[test]
fn a_hunk_whose_context_is_not_in_the_file_refuses() -> TestResult {
    let dir = repo()?;
    let bogus = "@@\n\
                 \x20this line is nowhere in the file\n\
                 -also absent\n\
                 +replacement\n";

    let output = hook(dir.path(), &update(MAPPED, bogus), Some("off"))?;

    assert!(
        output.contains(RULE_CONTENT_UNAVAILABLE),
        "no faithful reconstruction is possible, so refuse: {output}"
    );
    Ok(())
}

/// The cost of discarding the `@@` header: a hunk whose body occurs twice is
/// ambiguous to us even when codex would have resolved it. Refuse rather than
/// pick an occurrence.
#[test]
fn an_ambiguous_hunk_refuses_rather_than_picking_an_occurrence() -> TestResult {
    let dir = repo()?;
    // `  log();` appears twice, and the discarded `@@` header is exactly what
    // codex would have used to tell them apart.
    let ambiguous = "@@\n\
                     -  log();\n\
                     +  trace();\n";

    let output = hook(dir.path(), &update(DUPES, ambiguous), Some("off"))?;

    assert!(
        output.contains(RULE_CONTENT_UNAVAILABLE),
        "an ambiguous hunk must refuse: {output}"
    );
    Ok(())
}

/// A rename means the reconstructed content lands at the DESTINATION while the
/// source ceases to exist. Judging the right bytes against the wrong path's
/// rules is a false verdict, so the CONTENT judgement is withheld — while F58's
/// path rules still cover both ends.
#[test]
fn a_move_to_withholds_content_synthesis() -> TestResult {
    let dir = repo()?;
    let moved = format!("*** Update File: {MAPPED}\n*** Move to: docs/moved.ts\n{BREAK_HUNK}");

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

    assert!(
        output.contains(RULE_CONTENT_UNAVAILABLE),
        "a rename is not modelled by this arm; refuse rather than judge the \
         content against the wrong path: {output}"
    );
    Ok(())
}

/// F58's path gating is unchanged by this arm.
#[test]
fn a_move_to_a_protected_path_is_still_denied() -> TestResult {
    let dir = repo()?;
    let moved = format!("*** Update File: {ORDINARY}\n*** Move to: pushkin.toml\n@@\n-one\n+uno\n");

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

    assert!(output.contains(RULE_PROTECTED), "{output}");
    Ok(())
}

// ---------------------------------------------------------------------------
// Mixed patches
// ---------------------------------------------------------------------------

/// An `*** Add File:` section carries a WHOLE file. Inside a patch that also
/// updates something, the whole patch takes the mutation intent — but the added
/// file needs no reconstruction, so its content must still be judged rather
/// than refused for lack of edits it never needed.
#[test]
fn an_add_alongside_an_update_still_judges_the_added_content() -> TestResult {
    let dir = repo()?;
    let mixed = format!(
        "*** Add File: app/api/new/route.ts\n\
         +export async function POST(req: Request) {{\n\
         +  const body = await req.json();\n\
         +  return Response.json(body);\n\
         +}}\n\
         *** Update File: {ORDINARY}\n\
         @@\n\
         -two\n\
         +three\n"
    );

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

    assert!(
        output.contains(RULE_UNVALIDATED),
        "the added handler parses no contract and must be caught: {output}"
    );
    Ok(())
}

// ---------------------------------------------------------------------------
// Ordering, warm/cold, and the neighbouring arms
// ---------------------------------------------------------------------------

#[test]
fn a_read_only_path_denies_before_synthesis_is_attempted() -> TestResult {
    let dir = repo()?;
    let hunk = "@@\n-// committed suite\n+// tampered\n";

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

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

#[test]
fn the_synthesis_verdict_is_identical_warm_and_cold() -> TestResult {
    let dir = repo()?;
    let payload = update(MAPPED, BREAK_HUNK);

    let cold = hook(dir.path(), &payload, Some("off"))?;
    let warm = hook(dir.path(), &payload, Some("auto"))?;
    stop_daemon(dir.path());

    for output in [&cold, &warm] {
        assert!(output.contains(RULE_UNVALIDATED), "{output}");
        assert!(!output.contains(RULE_CONTENT_UNAVAILABLE), "{output}");
    }
    Ok(())
}

/// Regression on F58: deletes are still decided by the path rules alone.
#[test]
fn a_delete_only_patch_is_unaffected() -> TestResult {
    let dir = repo()?;

    let output = hook(
        dir.path(),
        &patch_payload("*** Delete File: pushkin.toml\n"),
        Some("off"),
    )?;

    assert!(output.contains(RULE_PROTECTED), "{output}");
    assert!(!output.contains(RULE_CONTENT_UNAVAILABLE), "{output}");
    Ok(())
}

/// Regression: an Add-only patch is a whole file and keeps its content verdict.
#[test]
fn an_add_only_patch_is_unaffected() -> TestResult {
    let dir = repo()?;

    let output = hook(
        dir.path(),
        &patch_payload(
            "*** Add File: app/api/other/route.ts\n\
             +export async function POST(req: Request) {\n\
             +  const body = await req.json();\n\
             +  return Response.json(body);\n\
             +}\n",
        ),
        Some("off"),
    )?;

    assert!(output.contains(RULE_UNVALIDATED), "{output}");
    Ok(())
}