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
//! N13 fail-open floor (B1/B3): the generated pre-commit floor degrades on
//! positively probed absence and NEVER on a check that ran.
//!
//! Decided input (Amos 2026-08-14, ratified same-day rider; IDEAS.md:17 and
//! the B4 fidelity line at IDEAS.md:21): fail open ONLY when the `pushkin`
//! binary or `pushkin.toml` is positively detected absent โ€” loud stderr
//! notice, exit 0. A check that RUNS passes its exit through untouched: 2
//! blocks, any other nonzero (e.g. 1 from a broken manifest) blocks loudly
//! with the check's own error text. No error class of a check that ran fails
//! open, and there is NO exit-code case analysis in the emitted scalar.
//!
//! Method per charter Addendum 1: the guard is EXECUTED, and the emitted
//! config is proven valid by real `lefthook validate` / `lefthook run` โ€” not
//! by substring assertions, which is the gap that admitted F-A/F-B.
//!
//! Committed first, read-only hereafter (charter ยง4.1, N10).

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]
protected_paths = ["pushkin.toml"]
"#;

/// Mirrors the canonical contract fixture used by `check_staged.rs`, so the
/// gate recognizes the parse call by the schema name it actually emits.
const CONTRACT: &str = "import { z } from \"zod\";\n\
                        export const UserCreateSchema = z.object({ name: z.string() });\n\
                        export type UserCreate = z.infer<typeof UserCreateSchema>;\n";

/// An unvalidated boundary handler: `pushkin check` reports this as a
/// violation, which is the "blocks" shape.
const VIOLATION: &str = "export async function POST(req: Request) {\n  \
                         const body = await req.json();\n  \
                         return Response.json({ name: body.name });\n}\n";

/// A handler that parses at the boundary โ€” the "passes" shape.
const COMPLIANT: &str = "import { UserCreateSchema } from \"../../../contracts/user.zod\";\n\n\
                         export async function POST(req: Request) {\n  \
                         const body = UserCreateSchema.parse(await req.json());\n  \
                         return Response.json(body);\n}\n";

const FLOOR: &str = "lefthook.yml";

/// A real git repo with a staged tree โ€” `check --staged` needs an index.
fn staged_repo(handler: &str) -> Result<tempfile::TempDir, Box<dyn std::error::Error>> {
    let dir = tempfile::tempdir()?;
    let root = dir.path();
    fs::write(root.join("pushkin.toml"), MANIFEST)?;
    fs::create_dir_all(root.join("contracts"))?;
    fs::create_dir_all(root.join("app/api/users"))?;
    fs::write(root.join("contracts/user.zod.ts"), CONTRACT)?;
    fs::write(root.join("app/api/users/route.ts"), handler)?;
    git(root, &["init", "-q", "."])?;
    git(root, &["add", "-A"])?;
    Ok(dir)
}

fn git(root: &Path, args: &[&str]) -> Result<(), Box<dyn std::error::Error>> {
    let status = StdCommand::new("git")
        .current_dir(root)
        .args(args)
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()?;
    if !status.success() {
        return Err(format!("git {args:?} failed").into());
    }
    Ok(())
}

/// The directory holding the binary under test, so PATH can be set
/// explicitly rather than inherited (ambient-PATH independence).
fn binary_dir() -> Result<String, Box<dyn std::error::Error>> {
    Ok(Path::new(env!("CARGO_BIN_EXE_pushkin"))
        .parent()
        .ok_or("binary under test has no parent")?
        .to_string_lossy()
        .into_owned())
}

/// A PATH carrying the binary under test AND the system tools `pushkin check`
/// itself shells out to (`git`). Explicit, never inherited wholesale.
fn provisioned_path() -> Result<String, Box<dyn std::error::Error>> {
    Ok(format!("{}:/usr/bin:/bin", binary_dir()?))
}

fn install_floor(root: &Path) -> Result<(), Box<dyn std::error::Error>> {
    let output = Command::cargo_bin("pushkin")?
        .current_dir(root)
        .env("PATH", binary_dir()?)
        .args(["init", "--agent", "lefthook"])
        .output()?;
    if !output.status.success() {
        return Err("init --agent lefthook failed".into());
    }
    Ok(())
}

/// The guard body as emitted, extracted from the generated YAML so the tests
/// execute exactly what ships โ€” never a re-typed copy.
fn emitted_guard(root: &Path) -> Result<String, Box<dyn std::error::Error>> {
    let yaml = fs::read_to_string(root.join(FLOOR))?;
    let mut body = String::new();
    let mut inside = false;
    for line in yaml.lines() {
        if line.trim_start().starts_with("run:") {
            inside = true;
            continue;
        }
        if inside {
            if line.trim_start().starts_with("# pushkin:end") {
                break;
            }
            let stripped = line.strip_prefix("        ").unwrap_or(line.trim_start());
            body.push_str(stripped);
            body.push('\n');
        }
    }
    if body.trim().is_empty() {
        return Err(format!("no run: body found in emitted floor:\n{yaml}").into());
    }
    Ok(body)
}

/// Runs the emitted guard under an EXPLICIT PATH, returning (exit, stderr).
fn run_guard(
    root: &Path,
    path_value: &str,
) -> Result<(Option<i32>, String), Box<dyn std::error::Error>> {
    let script = root.join("pushkin-guard.sh");
    fs::write(&script, emitted_guard(root)?)?;
    let output = StdCommand::new("/bin/sh")
        .current_dir(root)
        .arg(&script)
        .env("PATH", path_value)
        .output()?;
    Ok((
        output.status.code(),
        String::from_utf8_lossy(&output.stderr).into_owned(),
    ))
}

// ---------- fail-open: the two probe legs ----------

#[test]
fn binary_absent_fails_open_with_a_loud_notice() -> TestResult {
    let dir = staged_repo(VIOLATION)?;
    install_floor(dir.path())?;

    // Manifest present, binary unreachable: isolates the binary leg.
    let (code, stderr) = run_guard(dir.path(), "")?;
    assert_eq!(
        code,
        Some(0),
        "an absent binary must fail OPEN, not block the commit: {stderr}"
    );
    assert!(
        stderr.contains("pushkin"),
        "the fail-open must be loud on stderr: {stderr:?}"
    );
    Ok(())
}

#[test]
fn manifest_absent_fails_open_with_a_loud_notice() -> TestResult {
    let dir = staged_repo(VIOLATION)?;
    install_floor(dir.path())?;
    fs::remove_file(dir.path().join("pushkin.toml"))?;

    let (code, stderr) = run_guard(dir.path(), &provisioned_path()?)?;
    assert_eq!(code, Some(0), "an absent manifest must fail OPEN: {stderr}");
    assert!(
        stderr.contains("pushkin"),
        "the fail-open must be loud on stderr: {stderr:?}"
    );
    Ok(())
}

#[test]
fn the_notice_names_both_probe_legs_and_carries_a_hint() -> TestResult {
    let dir = staged_repo(COMPLIANT)?;
    install_floor(dir.path())?;
    let (_, stderr) = run_guard(dir.path(), "")?;

    assert!(
        stderr.contains("pushkin.toml"),
        "the notice must name the manifest leg so the reader can tell which fired: {stderr:?}"
    );
    assert!(
        stderr.to_lowercase().contains("failing open"),
        "the notice must say it is failing open: {stderr:?}"
    );
    assert!(
        stderr.contains("README") || stderr.contains("install"),
        "the notice must carry an actionable hint: {stderr:?}"
    );
    Ok(())
}

// ---------- exit passthrough: a check that RUNS is never touched ----------

#[test]
fn provisioned_violation_blocks_with_exit_two() -> TestResult {
    let dir = staged_repo(VIOLATION)?;
    install_floor(dir.path())?;

    let (code, stderr) = run_guard(dir.path(), &provisioned_path()?)?;
    assert_eq!(
        code,
        Some(2),
        "a staged violation must block with the check's own exit 2: {stderr}"
    );
    Ok(())
}

#[test]
fn provisioned_clean_tree_passes_with_exit_zero() -> TestResult {
    let dir = staged_repo(COMPLIANT)?;
    install_floor(dir.path())?;

    let (code, stderr) = run_guard(dir.path(), &provisioned_path()?)?;
    assert_eq!(code, Some(0), "a compliant staged tree must pass: {stderr}");
    Ok(())
}

/// The rider's sharp edge: a check that RUNS and ERRORS must block loudly,
/// never fail open. This is the case the superseded wide scope got wrong.
#[test]
fn broken_manifest_blocks_loudly_and_never_fails_open() -> TestResult {
    let dir = staged_repo(VIOLATION)?;
    install_floor(dir.path())?;
    fs::write(dir.path().join("pushkin.toml"), "version = 1\nbroken [[[\n")?;

    let (code, stderr) = run_guard(dir.path(), &provisioned_path()?)?;
    assert_ne!(
        code,
        Some(0),
        "a check that RAN and errored must NOT fail open: {stderr}"
    );
    assert!(
        !stderr.to_lowercase().contains("failing open"),
        "the fail-open notice must not fire for a check that ran: {stderr:?}"
    );
    assert!(
        stderr.contains("pushkin.toml") || stderr.contains("manifest") || stderr.contains("TOML"),
        "the check's own error text must reach the developer: {stderr:?}"
    );
    Ok(())
}

// ---------- the emitted scalar's shape ----------

#[test]
fn the_guard_carries_no_exit_code_case_analysis() -> TestResult {
    let dir = staged_repo(COMPLIANT)?;
    install_floor(dir.path())?;
    let guard = emitted_guard(dir.path())?;

    for forbidden in ["$?", "case ", "-eq 1", "-eq 2", "elif"] {
        assert!(
            !guard.contains(forbidden),
            "the scalar must contain NO exit-code case analysis (found {forbidden:?}); \
             passthrough is `exec`'s job: {guard}"
        );
    }
    assert!(
        guard.contains("exec pushkin check --staged --json"),
        "the provisioned path must exec the spec ยง17 command: {guard}"
    );
    Ok(())
}

/// The capture form is REQUIRED: a `/dev/null` redirect would introduce a
/// slash and break the committed `/`-invariant at `lefthook_floor.rs:97`.
#[test]
fn the_emitted_floor_contains_no_slash_at_all() -> TestResult {
    let dir = staged_repo(COMPLIANT)?;
    install_floor(dir.path())?;
    let yaml = fs::read_to_string(dir.path().join(FLOOR))?;

    assert!(
        !yaml.contains('/'),
        "no slash may appear anywhere in the emitted floor โ€” not in the guard, \
         the notice, or the install hint (the committed /-invariant): {yaml}"
    );
    assert!(
        yaml.contains("command -v pushkin"),
        "the probe must use the capture form, not a redirect: {yaml}"
    );
    Ok(())
}

#[test]
fn the_floor_carries_the_v3_marker() -> TestResult {
    let dir = staged_repo(COMPLIANT)?;
    install_floor(dir.path())?;
    let yaml = fs::read_to_string(dir.path().join(FLOOR))?;

    assert!(
        yaml.contains("pushkin-v3"),
        "marker bumped so the v2 (pre-guard) format is detectable: {yaml}"
    );
    Ok(())
}

// ---------- proven through lefthook itself, not just the raw scalar ----------

/// `lefthook` is a dev-environment tool; skip rather than fail where it is
/// absent so the suite stays honest on machines without it.
fn lefthook_available() -> bool {
    StdCommand::new("lefthook")
        .arg("version")
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()
        .is_ok_and(|status| status.success())
}

fn lefthook_path() -> Result<String, Box<dyn std::error::Error>> {
    let mut path = binary_dir()?;
    if let Ok(system) = std::env::var("PATH") {
        path.push(':');
        path.push_str(&system);
    }
    Ok(path)
}

#[test]
fn the_emitted_config_is_valid_per_real_lefthook_validate() -> TestResult {
    if !lefthook_available() {
        return Ok(());
    }
    let dir = staged_repo(COMPLIANT)?;
    install_floor(dir.path())?;

    let output = StdCommand::new("lefthook")
        .current_dir(dir.path())
        .arg("validate")
        .output()?;
    assert!(
        output.status.success(),
        "real `lefthook validate` must accept the emitted config โ€” substring \
         assertions are insufficient (the F-A/F-B gap): {}{}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );
    Ok(())
}

#[test]
fn lefthook_run_blocks_a_violation_when_provisioned() -> TestResult {
    if !lefthook_available() {
        return Ok(());
    }
    let dir = staged_repo(VIOLATION)?;
    install_floor(dir.path())?;

    let output = StdCommand::new("lefthook")
        .current_dir(dir.path())
        .env("PATH", lefthook_path()?)
        .args(["run", "pre-commit"])
        .output()?;
    assert!(
        !output.status.success(),
        "through lefthook itself, a staged violation must fail the hook: {}{}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );
    Ok(())
}

#[test]
fn lefthook_run_passes_with_a_notice_when_unprovisioned() -> TestResult {
    if !lefthook_available() {
        return Ok(());
    }
    let dir = staged_repo(VIOLATION)?;
    install_floor(dir.path())?;

    // A PATH with lefthook but deliberately WITHOUT pushkin.
    let system = std::env::var("PATH").unwrap_or_default();
    let without_pushkin: Vec<_> = std::env::split_paths(&system)
        .filter(|dir| !dir.join("pushkin").is_file())
        .collect();
    let path = std::env::join_paths(without_pushkin)?;

    let output = StdCommand::new("lefthook")
        .current_dir(dir.path())
        .env("PATH", &path)
        .args(["run", "pre-commit"])
        .output()?;
    let combined = format!(
        "{}{}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );
    assert!(
        output.status.success(),
        "an unprovisioned teammate's commit must NOT be blocked: {combined}"
    );
    assert!(
        combined.contains("failing open"),
        "the notice must reach the developer through lefthook: {combined}"
    );
    Ok(())
}